LeetCode #6 Medium

Zigzag Conversion

Zigzag Conversion is LeetCode 6 (Medium). Write the string s in a zigzag pattern over numRows rows: straight down from row 0 to the last row, then diagonally back up to row 0, then down again, until the characters run out. Return the rows read left to right, top row first.

s has at most 1,000 characters and numRows can be anything from 1 to 1,000, so even drawing a full grid would pass; the point is to see that no grid is needed.

Constraints
  • 1 <= s.length <= 1000
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • 1 <= numRows <= 1000
stringsimulation
Open on LeetCode ↗
02

Intuition

The drawing has columns and blank cells, but the answer never uses them: reading row by row only needs which row each character lands in, in the order it arrives. So keep one growing string per row and walk through s once.

The row number moves like a ball bouncing between two walls: 0, 1, …, numRows − 1, then back up to 0, and down again. Keep a step of +1 or −1 and flip it whenever the row reaches the top or the bottom. Characters reach each row in the same left-to-right order as in the drawing, so joining the rows from top to bottom gives the answer.

How to spot this pattern

When a string is laid out in some shape and then read back in another order, check whether only each character's group (here, its row) matters. If so, append to per-group buffers instead of building the shape.

03

Approach

Try it first

Before reading on, write the row number of each character of PAYPALISHIRING for 3 rows and look at the sequence. Then decide when that sequence changes direction. Aim for O(n) time.

1

Return early for one row

If numRows is 1, return s as it is: a single row read left to right is the string itself.

2

Append, then bounce

For each character, append it to rows[cur]. If cur is 0 or numRows − 1, the walk has hit a wall, so flip step; then add step to cur. Starting with step = -1 makes the first flip, at row 0, point the walk downward.

3

Join the rows

Concatenate rows[0], rows[1], … in order. Each row already holds its characters in left-to-right order, because the walk visits the drawing's columns from left to right, so the join is exactly the row-by-row reading.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def convert(self, s: str, numRows: int) -> str:
▶3 if numRows == 1:
▶4 return s
▶5 rows = [""] * numRows
▶6 cur, step = 0, -1
▶7 for ch in s:
▶8 rows[cur] += ch
▶9 if cur == 0 or cur == numRows - 1:
▶10 step = -step
▶11 cur += step
▶12 return "".join(rows)
012row 0row 1row 23 empty rows, walk starts at row 0
cur0
step-1flips to +1 at row 0
The dashed circles show where each of the 14 characters will land. Only the row matters, so keep one string per row; the columns are never stored.
012Prow 0Prow 1row 2P → row 0, top wall: turn down
charP
row0
next row1
Append P to row 0. Row 0 is the top wall, so the step becomes +1 and the walk heads down.
012PArow 0Prow 1Arow 2A → row 1
charA
row1
next row2
Append A to row 1. Not a wall, so keep going down to row 2.
012PAYrow 0Prow 1Arow 2YY → row 2, bottom wall: turn up
charY
row2
next row1
Append Y to row 2. Row 2 is the bottom wall, so the step becomes −1 and the walk heads back up the diagonal.
012PAYProw 0Prow 1AProw 2YP → row 1
charP
row1
next row0
Append P to row 1. Not a wall, so keep going up to row 0.
012PAYPArow 0PArow 1AProw 2YA → row 0, top wall: turn down
charA
row0
next row1
Append A to row 0. Row 0 is the top wall, so the step becomes +1 and the walk heads down.
012PAYPALrow 0PArow 1APLrow 2YL → row 1
charL
row1
next row2
Append L to row 1. Not a wall, so keep going down to row 2.
012PAYPALIrow 0PArow 1APLrow 2YII → row 2, bottom wall: turn up
charI
row2
next row1
Append I to row 2. Row 2 is the bottom wall, so the step becomes −1 and the walk heads back up the diagonal.
012PAYPALISrow 0PArow 1APLSrow 2YIS → row 1
charS
row1
next row0
Append S to row 1. Not a wall, so keep going up to row 0.
012PAYPALISHrow 0PAHrow 1APLSrow 2YIH → row 0, top wall: turn down
charH
row0
next row1
Append H to row 0. Row 0 is the top wall, so the step becomes +1 and the walk heads down.
012PAYPALISHIrow 0PAHrow 1APLSIrow 2YII → row 1
charI
row1
next row2
Append I to row 1. Not a wall, so keep going down to row 2.
012PAYPALISHIRrow 0PAHrow 1APLSIrow 2YIRR → row 2, bottom wall: turn up
charR
row2
next row1
Append R to row 2. Row 2 is the bottom wall, so the step becomes −1 and the walk heads back up the diagonal.
012PAYPALISHIRIrow 0PAHrow 1APLSIIrow 2YIRI → row 1
charI
row1
next row0
Append I to row 1. Not a wall, so keep going up to row 0.
012PAYPALISHIRINrow 0PAHNrow 1APLSIIrow 2YIRN → row 0, top wall: turn down
charN
row0
next row1
Append N to row 0. Row 0 is the top wall, so the step becomes +1 and the walk heads down.
012PAYPALISHIRINGrow 0PAHNrow 1APLSIIGrow 2YIRG → row 1
charG
row1
next row–
Append G to row 1. That was the last character.
012PAYPALISHIRINGrow 0PAHNrow 1APLSIIGrow 2YIRanswer: PAHNAPLSIIGYIR
answer"PAHNAPLSIIGYIR"
Join the rows from top to bottom. Each row already lists its characters left to right, so this is the zigzag read row by row.
05

Common pitfalls

Skipping the one-row check

✗ Wrong
rows = [""] * numRows
cur, step = 0, -1
✓ Right
if numRows == 1:
    return s
rows = [""] * numRows

With one row, row 0 is the top and the bottom at once. For s = "AB", the first character flips step to +1 and moves cur to 1, a row that does not exist, so the second append crashes with an index error.

06

Edge cases

numRows at least the length of s, e.g. "ABC" with 5 rows

The walk goes straight down, one character per row, and runs out before reaching the bottom wall. Each row holds one character, so the answer is s unchanged.

numRows = 2

Both rows are walls, so the step flips on every character and the rows alternate. The answer is the characters at even positions followed by those at odd positions: "ABCDE" gives "ACEBD".

07

Complexity

Time
O(n)
Space
O(n)
n is the length of s. Each character is appended once and copied once more by the join. The row strings together hold n characters.
08

Zigzag Conversion FAQ

Can each row be built without simulating the walk?

Yes. The pattern repeats every cycle = 2 · numRows − 2 characters. Row 0 takes indices 0, cycle, 2 · cycle, …, and the last row takes numRows − 1 plus multiples of cycle. A middle row r takes k · cycle + r and, after each of those, the diagonal character at k · cycle + cycle − r. It writes the answer directly, also in O(n).

Is Concatenation of Zig-Zag String in n Rows the same problem?

Yes. It asks for the same thing: write the string in the zigzag shape and print the rows joined together. The row-bounce walk on this page solves it unchanged.