Zigzag Conversion (LeetCode 6): Solution and Explanation
Write the characters of s down numRows rows, then diagonally back up to the top, over and over, like a zigzag. Read the finished pattern row by row from left to right and return that string.
Intuition
The picture in the problem suggests building a 2D grid with columns and blank cells, then scanning it row by row. That works, but most of the grid is empty space, and the columns do not matter at all for the answer.
What matters is which row each character lands in. Within a single row, characters appear in the same order they had in s, because the zigzag only ever moves to the right. So if you append every character to its row's buffer as you go, each buffer already holds that row's text in reading order.
The row sequence is easy to produce. Start at row 0 and move down one row per character. When you reach the last row, the direction flips and you move up one row per character. When you reach row 0 again, it flips back. A single variable step that is +1 or -1 captures the whole walk.
Two inputs have no zigzag at all. With one row the walk cannot move, and with at least as many rows as characters the walk never reaches the bottom to bounce. In both cases the answer is s itself, so return it right away. The one-row check also prevents the bounce logic from flipping between +1 and -1 on the same row.
Approach: Row buffers with a bouncing pointer
- If
numRows == 1ornumRows >= len(s), returnsunchanged. - Create
numRowsempty row buffers, and setrow = 0andstep = 1. - For each character, append it to
rows[row]. - If
rowis 0, setstep = 1(head down). IfrowisnumRows - 1, setstep = -1(head up). Then move withrow += step. - After the loop, concatenate the rows from top to bottom and return the result.
Step-by-step example
s = "PAYPALISHIRING", numRows = 3
- 3 is between 2 and 13, so the shortcut does not apply. Start with rows
["", "", ""],row = 0,step = +1. - P goes to row 0, A to row 1, Y to row 2. Row 2 is the bottom, so
stepbecomes -1. - P goes up to row 1, then A lands on row 0, the top, so
stepbecomes +1 again. - The pattern repeats: L to row 1, I to row 2 (bounce), S to row 1, H to row 0 (bounce), I to row 1, R to row 2 (bounce), I to row 1, N to row 0, G to row 1.
- The rows end as
"PAHN","APLSIIG"and"YIR". - Joining them top to bottom gives
"PAHNAPLSIIGYIR".
Code: Python, Java, C++
1class Solution:
2 def convert(self, s: str, numRows: int) -> str:
3 if numRows == 1 or numRows >= len(s):
4 return s
5 rows = [''] * numRows
6 row, step = 0, 1
7 for ch in s:
8 rows[row] += ch
9 if row == 0:
10 step = 1
11 elif row == numRows - 1:
12 step = -1
13 row += step
14 return ''.join(rows)1class Solution {
2 public String convert(String s, int numRows) {
3 if (numRows == 1 || numRows >= s.length()) {
4 return s;
5 }
6 StringBuilder[] rows = new StringBuilder[numRows];
7 for (int i = 0; i < numRows; i++) rows[i] = new StringBuilder();
8 int row = 0, step = 1;
9 for (char ch : s.toCharArray()) {
10 rows[row].append(ch);
11 if (row == 0) {
12 step = 1;
13 } else if (row == numRows - 1) {
14 step = -1;
15 }
16 row += step;
17 }
18 StringBuilder result = new StringBuilder();
19 for (StringBuilder sb : rows) result.append(sb);
20 return result.toString();
21 }
22}1class Solution {
2public:
3 string convert(string s, int numRows) {
4 if (numRows == 1 || numRows >= (int)s.size()) {
5 return s;
6 }
7 vector<string> rows(numRows);
8 int row = 0, step = 1;
9 for (char ch : s) {
10 rows[row] += ch;
11 if (row == 0) {
12 step = 1;
13 } else if (row == numRows - 1) {
14 step = -1;
15 }
16 row += step;
17 }
18 string result;
19 for (const string& r : rows) result += r;
20 return result;
21 }
22};Time and space complexity
O(n)
Each character is appended to exactly one row buffer, and the final join copies each character once more, so the work is linear in the length of s.
O(n)
The row buffers together hold every character of s once, plus the output string.
Other approaches
Build the 2D grid (time O(numRows * n), space O(numRows * n))
Allocate a numRows by columns grid, place each character at its (row, column) position as you walk the zigzag, then scan the grid row by row and skip blanks. It mirrors the picture exactly, which helps when first learning the problem, but it wastes memory on empty cells.
Visit by row with the cycle formula (time O(n), space O(1) besides the output)
The pattern repeats every cycle = 2 * numRows - 2 characters. For row r, take indices r, r + cycle, r + 2 * cycle, ..., and for the middle rows also the diagonal index k + cycle - r between them. This writes the answer directly in order with no row buffers beyond the output.
Common mistakes
- Skipping the
numRows == 1check. Row 0 is then also the last row, the direction flips every character, androwwalks to -1 or out of range. - Flipping the direction before appending the character, which puts the bounce character into the wrong row.
- Moving diagonally by changing the row by 2 or skipping rows. Each step of the walk changes the row by exactly one.
- Concatenating strings inside a loop in a language where that copies the whole string each time. Use a list, StringBuilder or byte slice per row.
Frequently asked questions
Why don't I need to track columns?
The answer only depends on the order of characters within each row. Because the zigzag always moves left to right, appending characters to their row in the order they arrive already gives the correct left to right order.
What happens when numRows is larger than the string length?
The walk goes straight down and runs out of characters before it ever reaches the bottom row, so each character sits alone in its own row. Reading the rows top to bottom returns the original string.
How many characters are in one full zigzag cycle?
One cycle covers 2 * numRows - 2 characters: numRows going down the column and numRows - 2 on the diagonal back up, since the top and bottom rows are shared with the neighbouring columns.
What is the time complexity of Zigzag Conversion?
It is O(n) time and O(n) space for the simulation approach. Each character is written to one row and copied once into the result.