InterviewPrepKit

Home / Coding / Math & Geometry

Zigzag Conversion

medium Original β†—
Solving tips
  • Simplest reliable approach: keep one buffer per row, append each char to its current row, and bounce the row pointer direction at row 0 and row numRows-1.
  • No real columns are needed; appending in visitation order already gives the correct left-to-right ordering within each row.
  • Guard numRows==1 (and numRows>=len(s)) early to return s and avoid an infinite loop / zero-length stride.
  • Target O(n) time and O(n) space; the closed-form variant uses cycle = 2*numRows-2 where middle rows get an extra diagonal char at offset cycle-r.

Problem

Take a string s and write it out in a zigzag pattern across a fixed number of rows numRows, moving down the rows then diagonally back up, repeatedly. Then read the grid row by row (left to right, top to bottom) and return that as a single string.

For example, "PAYPALISHIRING" with 3 rows is laid out as:

P   A   H   N
A P L S I I G
Y   I   R

Reading row by row gives "PAHNAPLSIIGYIR".

Examples

  • s = "PAYPALISHIRING", numRows = 3 β†’ "PAHNAPLSIIGYIR".
  • s = "PAYPALISHIRING", numRows = 4 β†’ "PINALSIGYAHRPI" β€” the pattern goes down 4, then diagonally up.
  • s = "AB", numRows = 1 β†’ "AB" β€” one row means no zigzag; the string is unchanged.

Constraints

  • 1 <= len(s) <= 1000
  • s consists of English letters (upper/lower), commas, and periods.
  • 1 <= numRows <= 1000
  • When numRows == 1 (or numRows >= len(s)), there is no zigzag and the output equals the input.

Think about it first

Hint 1 Simulate the writing. Keep one string buffer per row. Append each character to the current row, moving the "current row" pointer down until you hit the bottom, then up until you hit the top, reversing direction at each edge.
Hint 2 The `numRows == 1` case has no "down then up" β€” guard it so you don't divide by zero or loop forever.
Hint 3 There's also a closed-form: one full zigzag "cycle" spans `2 * numRows - 2` characters. For each row you can compute exactly which indices of `s` fall in it, skipping the row-buffer simulation entirely.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.