SDE & MLE Prep

6. Zigzag Conversion

Problem

Write s in a zigzag over numRows rows (down the rows, then diagonally back up, repeatedly), then read the rows top to bottom and return the result.

Example: s = "PAYPALISHIRING", numRows = 3 → "PAHNAPLSIIGYIR" (rows PAHN, APLSIIG, YIR)

Simulate writing the zigzag: keep one buffer per row and a cursor that moves down, bounces at the last row, moves up, bounces at row 0. Reading the rows top to bottom gives the answer.

"PAYPALISHIRING", numRows = 4        cursor: 0 1 2 3 2 1 0 1 2 3 ...
row 0:  P     I     N
row 1:  A   L S   I G
row 2:  Y A   H R
row 3:  P     I
-> "PIN" + "ALSIG" + "YAHR" + "PI"

Complexity: O(n).

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