Zigzag Conversion

Medium

Topics
String

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

gridP···A···H···N··A·P·L·S·I·I·G··Y···I···R···
answerPAHNAPLSIIGYIR
a character of snothing written here
The characters are written down the first column, then diagonally back up to the top row, repeating, which is the placement the grid shows for 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.
The grid is a way of stating the problem, not the output; the output is a plain string.
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

gridP·····I·····N··A···L·S···I·G··Y·A···H·R······P·····I····
answerPINALSIGYAHRPI
a character of snothing written here
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

gridAB
answerAB
a character of s
With a single row there is nowhere to zigzag, so the answer is the input unchanged.
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

  1. Return s unchanged when k is 1, or make the walk safe for it.
  2. Keep one buffer per row, a current row starting at 0, and a step of +1.
  3. For each character, append it to the current row’s buffer, then flip the step to -1 at the bottom row and to +1 at row 0, and add the step.
  4. 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 -> PAHNAPLSIIGYIR

Complexity

  • 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 formula 2k - 2 is 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 = 1 both 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 k is 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)
SensAI
Beta
Tap the mic to stop voice mode