InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Zigzag Conversion

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug