Zigzag Conversion
Medium
Topics
Write s downwards across k rows, then diagonally back up to the first row, then downwards again, and so on — a zigzag.
So "PAYPALISHIRING" with k = 3 is written as:
P A H N
A P L S I I G
Y I R
Return the string formed by reading the rows left to right, top to bottom — here "PAHNAPLSIIGYIR".
The judge names the row count k; LeetCode calls it numRows.
Example 1
k = 3 rows. The answer reads that grid row by row, left to right, skipping the blanks — so characters that were far apart in s become neighbours whenever they share a row. The rows come out uneven in length, because only the top and bottom rows get a character in every diagonal.Input: s = "PAYPALISHIRING", k = 3 Output: "PAHNAPLSIIGYIR" Explanation: Row 0 collects P, A, H, N; row 1 collects the rest in zigzag order; row 2 collects Y, I, R.
Example 2
Input: s = "PAYPALISHIRING", k = 4 Output: "PINALSIGYAHRPI" Explanation: More rows means longer diagonals, so the middle rows pick up two characters per cycle.
Example 3
Input: s = "AB", k = 1 Output: "AB" Explanation: A single row never turns, so the string is unchanged — and the naive cycle length of 2k-2 is zero here, which is the case that divides by zero.
Constraints
- 1 <= s.length <= 1000
- s consists of English letters, commas and full stops
- 1 <= k <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
Nothing has to be laid out in two dimensions. Each character goes to exactly one row, and the answer is the rows concatenated, so the only question is which row each character belongs to.
Walking the string and tracking a row number with a direction answers that directly: start at row 0 moving down, and flip direction whenever you reach the top or bottom row. Append each character to its row’s buffer as you pass.
The k = 1 case is the one that breaks solutions. A single row never turns, so any formula built on a cycle length of 2k - 2 divides by zero — and the direction-flipping walk handles it only if the flip test is written so that top and bottom are the same row.
Approach
- Return
sunchanged whenkis 1, or make the walk safe for it. - Keep one buffer per row, a current row starting at 0, and a step of
+1. - For each character, append it to the current row’s buffer, then flip the step to
-1at the bottom row and to+1at row 0, and add the step. - Concatenate the buffers in row order.
Walkthrough
s = "PAYPALISHIRING", k = 3
char row step after
P 0 +1
A 1 +1
Y 2 -1 bottom row, turn
P 1 -1
A 0 +1 top row, turn
L 1 +1
I 2 -1
S 1 -1
H 0 +1
I 1 +1
R 2 -1
I 1 -1
N 0 +1
G 1 +1
row 0: P A H N
row 1: A P L S I I G
row 2: Y I R
concatenated -> PAHNAPLSIIGYIRComplexity
- Time — O(n): one pass, one append per character.
- Space — O(n): the row buffers hold the whole string between them.
Common Pitfalls
- Not handling
k = 1. The cycle-length formula2k - 2is 0 there, and the direction walk loops without moving unless the turn test is ordered correctly. - Checking for row 0 before checking for the bottom row. When
k = 1both are true of row 0 and the order decides whether the step ever becomes-1. - Building an actual
k-by-n grid of spaces. It works and it is a lot of memory for a layout nobody looks at. - Reading the grid column by column. The answer is row by row; the zigzag is only how the characters were placed.
- Assuming
kis at most the string length. It can be larger, in which case the zigzag never reaches the bottom and some rows stay empty.
Full Solution — all languages
class Solution:
def convert(self, s, k):
if k == 1:
return s
rows = [[] for _ in range(k)]
row, step = 0, 1
for c in s:
rows[row].append(c)
if row == k - 1:
step = -1
elif row == 0:
step = 1
row += step
return "".join("".join(r) for r in rows)import java.util.*;
class Solution {
public String convert(String s, int k) {
if (k == 1) return s;
StringBuilder[] rows = new StringBuilder[k];
for (int i = 0; i < k; i++) rows[i] = new StringBuilder();
int row = 0, step = 1;
for (char c : s.toCharArray()) {
rows[row].append(c);
if (row == k - 1) step = -1;
else if (row == 0) step = 1;
row += step;
}
StringBuilder out = new StringBuilder();
for (StringBuilder r : rows) out.append(r);
return out.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string convert(string s, int k) {
if (k == 1) return s;
vector<string> rows(k);
int row = 0, step = 1;
for (char c : s) {
rows[row] += c;
if (row == k - 1) step = -1;
else if (row == 0) step = 1;
row += step;
}
string out;
for (const string& r : rows) out += r;
return out;
}
};/**
* @param {string} s
* @param {number} k
* @return {string}
*/ var convert = function(s, k) {
if (k === 1) return s;
const rows = Array.from({ length: k }, () => []);
let row = 0, step = 1;
for (const c of s) {
rows[row].push(c);
if (row === k - 1) step = -1;
else if (row === 0) step = 1;
row += step;
}
return rows.map(r => r.join("")).join("");
};