← Create New Paste

Zigzag Conversion in a Coding Interview: From Row Simulation to the Cycle Formula

6 views
"Zigzag Conversion" (LeetCode 6) looks like a string puzzle, but interviewers use it to see whether you can turn a picture into an index rule. You write a string such as "PAYPALISHIRING" in a zigzag across numRows rows, then read it row by row. With 3 rows you get "PAHNAPLSIIGYIR". The trap is not the difficulty; it is the off-by-one errors that appear when candidates rush to code. Step 1: Draw it, then describe the motion Before writing anything, sketch four or five characters with numRows = 4. Characters go down rows 0, 1, 2, 3, then diagonally back up through rows 2 and 1, then down again. Say that out loud: "The row index bounces between 0 and numRows - 1." That sentence is basically your first solution. Step 2: The simulation approach Keep a list of numRows string builders, a current row, and a direction. For each character, append it to rows[current]. If current is 0, set direction to +1; if current is numRows - 1, set direction to -1. Then move current by direction. At the end, join all rows. This is O(n) time and O(n) extra space, easy to explain, and hard to get wrong. Mention the edge case before the interviewer does: if numRows is 1 or numRows is at least the string length, return the string unchanged. Without that guard, the direction logic flips forever on row 0 and you can index out of range. Step 3: The cycle formula A strong follow-up is to compute positions directly. One full down-and-up pass has length cycle = 2 * numRows - 2. For row 0 and the last row, characters appear at indexes j, j + cycle, j + 2*cycle, and so on. For a middle row r, each cycle contributes two characters: index k + r and index k + cycle - r, where k steps through 0, cycle, 2*cycle. You still produce n characters, so time stays O(n), but you avoid the per-row buffers except for the output. Walk through row 1 with numRows = 3 to prove it: cycle = 4, so you take indexes 1, 3, 5, 7, 9, 11, 13 - the letters A, P, L, S, I, I, G. That matches the middle row of the expected answer, and showing that check builds a lot of trust. How to talk while coding Interviewers here mostly grade clarity. State the invariant ("current is always a valid row"), name the guard, and test with numRows = 1, 2, and a string shorter than numRows. If you go for the formula version, explain why middle rows get two characters per cycle instead of just asserting it. Practicing out loud helps more than reading solutions. Some candidates also use Linkjob AI (https://linkjob.ai), which gives real-time help during live job interviews and technical interviews, to keep their structure steady when nerves make them skip steps. Whatever tools you use, the goal is the same: picture, invariant, edge cases, then code.
Created Nov 17, 2026 13:31 Expires Nov 17, 2027 13:31