LeetCode 6: Zigzag Conversion — Python Solution

LeetCode 6: Zigzag Conversion is a Medium array / string problem. This Python walkthrough develops a row simulation solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicArray / String
Reusable patternrow simulation
ComplexityO(n) time and O(n) space

Recognizing the pattern

Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.

For this problem specifically, walk down and up across row buffers, reversing direction at the first and last row, then concatenate the rows. The invariant worth writing beside the code is: Each processed character is appended to the row visited by the zigzag cursor.

Step-by-step algorithm

  1. Identify the input state consumed by convert(s, numRows) and initialize the data required by the row simulation pattern.
  2. Walk down and up across row buffers, reversing direction at the first and last row, then concatenate the rows.
  3. After each update, verify the page’s central invariant: Each processed character is appended to the row visited by the zigzag cursor.
  4. Finish only after the boundary behavior is covered: One row or at least as many rows as characters returns the original string.

Python solution

class Solution:
    def convert(self, s, numRows):
        if numRows == 1 or numRows >= len(s):
            return s
        rows = ["" for _ in range(numRows)]
        row, direction = 0, 1
        for char in s:
            rows[row] += char
            if row == 0:
                direction = 1
            elif row == numRows - 1:
                direction = -1
            row += direction
        return "".join(rows)

Reading the implementation

The main entry point is convert(s, numRows). The named working state includes rows, row, direction; those variables make the row simulation state visible instead of hiding it in incidental control flow.

A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, walk down and up across row buffers, reversing direction at the first and last row, then concatenate the rows.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Walk down and up across row buffers, reversing direction at the first and last row, then concatenate the rows. Each update records the current item without invalidating earlier decisions; consequently, each processed character is appended to the row visited by the zigzag cursor.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n) time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().convert("PAYPALISHIRING",3) == "PAHNAPLSIIGYIR"

Common mistakes and edge cases

  • Problem-specific boundary: One row or at least as many rows as characters returns the original string.
  • Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
  • Invariant check: after every update, confirm that each processed character is appended to the row visited by the zigzag cursor.

Interview review checklist

  • Explain why row simulation matches the structure of this input.
  • State the invariant in one sentence before tracing code: Each processed character is appended to the row visited by the zigzag cursor.
  • Derive O(n) time and O(n) space from how many times each element or state is visited.
  • Test the boundary explicitly: One row or at least as many rows as characters returns the original string.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 151. Reverse Words in a String · Next: 28. Find the Index of the First Occurrence in a String