LeetCode 6 Solution – ZigZag Conversion

L

In the LeetCode 6 – “Zigzag Conversion” problem, we are given a string s and an integer numRows. The string should be written in a zigzag pattern across numRows rows. After forming this zigzag pattern, the task is to read the characters row by row and return the resulting string.

For example, with the input string "PAYPALISHIRING" and numRows = 3, the zigzag pattern looks like:

P   A   H   N
A P L S I I G
Y   I   R

The output for this is "PAHNAPLSIIGYIR".

For numRows = 4, the zigzag pattern looks like:

P     I    N
A   L S  I G
Y A   H R
P     I

The output for this is "PINALSIGYAHRPI".

Analyzing the Constraints and Input

  1. Input String Length (1 <= s.length <= 1000): This means our solution needs to efficiently handle strings up to 1000 characters in length.
  2. Number of Rows (1 <= numRows <= 1000): There can be up to 1000 rows, and if numRows == 1, the zigzag pattern won’t exist—just return the string as is.
  3. Character Set: The string s contains English letters (both lowercase and uppercase), commas, and periods.

High-Level Algorithmic Approach

In this problem, we need to arrange characters from the string s into a zigzag pattern across numRows rows. However, we don’t need to worry about inserting spaces to align characters as shown in the examples. Our goal is simply to place the characters row by row while simulating the zigzag movement and then read them sequentially by rows.

Key Steps:

  1. Handle Special Case (numRows == 1): If there’s only one row, no zigzagging occurs. We can directly return the string s as it is.
  2. Simulating the Zigzag Pattern:
    – Create a list to represent each row. The list size will be the smaller of numRows and len(s) because if the string is shorter than numRows, we’ll only need as many rows as there are characters.
    – Traverse the string, placing each character in the correct row based on the current position and direction (either moving down or up between the rows).
  3. Switching Direction: When you reach the top or bottom row, reverse the direction. Start moving downward through the rows, and once you reach the last row, switch to moving upward.
  4. Concatenate the Rows: After all characters are placed in the rows, simply concatenate the contents of each row to get the final result.

By following these steps, the zigzag pattern is formed and the rows are read without worrying about visual spacing between characters.

Selecting the Data Structure

We’ll use a list of strings (or lists in Python) to represent each row. As we traverse through the string s, we’ll append each character to the appropriate row based on the current direction (down or up). After building the rows, we’ll concatenate them to form the final result.

LeetCode 6 – Code Implementation

def convert(s: str, numRows: int) -> str:
    # Edge case: If numRows is 1, return the original string
    if numRows == 1:
        return s

    # Create a list to hold strings for each row
    rows = [''] * min(numRows, len(s))  # Min because we might have fewer rows than the length of s

    # Initialize variables for tracking the current row and direction
    current_row = 0
    going_down = False

    # Traverse through each character in the string
    for char in s:
        # Append the character to the current row
        rows[current_row] += char

        # Change direction at the top and bottom rows
        if current_row == 0 or current_row == numRows - 1:
            going_down = not going_down

        # Move to the next row (down or up)
        current_row += 1 if going_down else -1

    # Concatenate all rows to form the final result
    return ''.join(rows)

Exploring Edge Cases

  • Case 1: Single Row (numRows = 1)
    If numRows is 1, there is no zigzagging, so we can return the original string. The early return if numRows == 1 handles this.
  • Case 2: Short String (s.length < numRows)If the string length is less than numRows, we can’t have a full zigzag pattern, but the rows array is sized appropriately using min(numRows, len(s)).
  • Case 3: Normal Case (numRows > 1 and s.length > numRows)The zigzag pattern is formed as expected, and characters are distributed across the rows while zigzagging up and down.

Time and Space Complexity Analysis

  • Time Complexity:
    The time complexity is O(n), where n is the length of the string s. We make a single pass through the string, appending characters to the appropriate rows.
  • Space Complexity:
    The space complexity is O(n) as well, since we store each character of the string into different rows, which in total holds the entire string.

LeetCode 6 Solution: Conclusion

In this problem, we efficiently solved the Zigzag Conversion by simulating the zigzag movement across rows. The algorithm handles both normal and edge cases (like when numRows is 1) and maintains a time complexity of O(n), which is optimal for the input constraints. This method is simple yet powerful for problems that involve pattern-based character placement!

Happy Coding!


Looking for more LeetCode solutions? Stay tuned for upcoming guides on tackling other LeetCode challenges in Python. Whether you’re preparing for technical interviews or aiming to improve your coding skills, exploring a variety of problems will enhance your understanding and proficiency.

You can find this problem on LeedCode, click here.

Add comment

By Peter

About me

Hi, I’m Peter, a professional developer with over 25 years of experience. My journey with coding started when I was just a kid, exploring the world of programming and building my first projects out of pure curiosity and passion. Since then, I’ve turned this lifelong passion into a rewarding career, working on a wide range of projects, from small scripts to complex applications.

Now, I’m here to help others get started with coding through this blog. I know that learning to code can feel overwhelming at first, but I believe that with the right guidance, anyone can develop the skills they need to become a proficient programmer. My goal is to simplify the learning process and provide step-by-step resources that make coding accessible, fun, and practical for everyone.

Whether you’re just starting out or looking to sharpen your skills, I hope this blog serves as a valuable resource on your coding journey. Let’s dive into Python together!

Get in touch

Have any questions or feedback? Feel free to reach out—I’m always happy to help you on your coding journey!

Tags