Zigzag Conversion solution explained

Zigzag Conversion is solved by simulating the pen: keep one buffer per row, drop each character into the current row, and reverse direction whenever you hit the top or bottom row; then join the rows. A faster-to-explain alternative computes positions directly, because the pattern repeats every 2 * (rows - 1) characters: row r takes index r of each cycle, and middle rows also take index cycle - r. Both are O(n) time; handle one row, or at least as many rows as characters, by returning the string unchanged.

By Published 7 min read

The problem in plain words

Imagine writing a word down a column, then diagonally back up and to the right until you reach the top row, then down the next column, and so on, like a saw blade. You are given the text and the number of rows. Return the characters as they read when you go along the first row from left to right, then the second row, down to the last. With the text INTERVIEWLOOP and four rows the layout looks like this:

@@zigzag-conversion/picture.txt@@
INTERVIEWLOOP over 4 rows: down I N T E, up R V, down I E W L, up O O, down P

Reading row by row gives IIP, then NVEO, then TRWO, then EL, so the answer is IIPNVEOTRWOEL.

Examples computed with the code on this page (text INTERVIEWLOOP unless noted)
RowsOutputComment
1INTERVIEWLOOPOne row means no zigzag at all
2ITRIWOPNEVELOEven positions, then odd positions
3IRWPNEVELOTIOCycle of 4 characters
4IIPNVEOTRWOELThe picture above; cycle of 6
13 (the length)INTERVIEWLOOPOne column, so the text is unchanged
2, text ABCDEACEBDOdd length: the first row gets the extra character
Examples computed with the code on this page (text INTERVIEWLOOP unless noted). Scroll sideways on a small screen.

Why it is asked

Zigzag tests whether you can model a process before coding it. There is no data structure insight to find; what separates answers is whether the candidate draws a small example, spots the repeating cycle, and handles the degenerate row counts. It also tests off-by-one discipline: the direction must flip on the first and last rows, not one step after them. Interviewers sometimes ask for the index-arithmetic version after the simulation, to see if you can derive a formula from the drawing.

Follow-ups

  • Decode it. Given the zigzag output and the row count, recover the original. Count how many characters each row holds using the same cycle arithmetic, slice the output into rows, then walk the zigzag again taking the next character from each row in turn.
  • Print the actual picture. Use the grid version, or compute the column for each index.
  • Stream the input. The row-buffer version works on a stream; the index version needs random access to the whole string.
  • Unicode text. In JavaScript, characters outside the Basic Multilingual Plane occupy two string positions, so split them with Array.from first if the text may contain emoji.

First version: draw it on a grid

Make a grid with numRows rows and as many columns as characters, which is always enough. Move the pen down a full column, then up one row and right one column at a time along the diagonal, writing a character at each stop. Finally read the grid row by row, skipping empty cells. Whether you are in a full column or on a diagonal can be decided by col % (numRows - 1) == 0. It is correct and mirrors the picture, but it allocates rows times length cells, most of them empty.

@@zigzag-conversion/slow.py@@
Python: literal simulation on a grid. O(rows * n) time and memory.

Expected version: one buffer per row and a bouncing pointer

Columns do not matter for the answer, only which row each character lands in. Keep a list per row and a current row with a step of +1 or -1. Append the character to the current row; if you are on the top row the step becomes +1, if on the bottom row it becomes -1; move. When the text runs out, join the rows. Every character is touched twice, once to place and once to join, and the total extra space is the size of the output.

@@zigzag-conversion/buckets.py@@
Python: row buffers with a direction that flips at the edges. O(n) time and space.

Index version: read each row straight from the input

The pen goes down numRows - 1 steps and up numRows - 1 steps, so the layout repeats every cycle = 2 * (numRows - 1) characters. Within the cycle starting at index k, row r holds the character at k + r on the way down, and, for rows strictly between the top and bottom, the character at k + cycle - r on the way up. The top and bottom rows get one character per cycle; the middle rows get two. Looping over rows, then over cycles, emits the output in order with no buffers at all. This is the version where a drawing on the whiteboard pays off, because the formula is easy to check against the picture: in the four-row example, row 1 takes indices 1, 5, 7 and 11.

@@zigzag-conversion/fast.py@@
Python: direct index arithmetic, O(n) time, O(1) besides the output.
@@zigzag-conversion/fast.js@@
JavaScript: the same arithmetic. JavaScript engines usually handle repeated += appends well.

Cost

n is the text length, R the number of rows
ApproachTimeExtra spaceNote
Grid simulationO(R * n)O(R * n)Matches the picture; wasteful
Row buffers and a direction flagO(n)O(n)Works on a stream
Cycle index arithmeticO(n)O(1) plus the outputNeeds the whole string
n is the text length, R the number of rows. Scroll sideways on a small screen.

Edge cases

  • One row: the cycle length would be 0, which breaks the index loop and the grid's modulo. Return the text as it is.
  • Rows at least as many as characters: every character sits in its own row of a single column, so again the text is unchanged.
  • Two rows: cycle 2, no middle rows, so the output is the even positions followed by the odd ones.
  • Empty text: the early return covers it.
  • Text length not a multiple of the cycle: the last cycle is partial, so both index checks must test against the length.

Common slips

  • Flipping direction after moving instead of before, which sends the row index to -1 or numRows.
  • Forgetting the numRows == 1 guard. The bouncing pointer then steps to row 1 of a one-row list and crashes, and in the index version the cycle becomes 0, which Python's range rejects and a JavaScript loop never leaves.
  • In the index version, adding the diagonal character on the top or bottom row, which duplicates characters (on those rows k + cycle - r equals the next cycle's start or the same index).
  • Building the output in an inner loop with string concatenation in a language where strings are immutable and appends copy, such as Java; use a builder there.

Talking it through

Fictional example

Draw first, then find the cycle
Candidate
Let me draw a short word on four rows first. Down four, back up two along the diagonal, then down again, so the shape repeats every six characters.
Candidate
The simplest correct code keeps one buffer per row and a pointer that bounces between the top and bottom. That's linear time.
Candidate
If you want no buffers: the cycle is two times rows minus one. Row r gets index r of each cycle, and middle rows also get cycle minus r. I'll check that against the drawing before I code it.
Candidate
Special cases: one row, or more rows than letters, both return the input unchanged.

String to Integer (atoi) is another string problem that rewards pinning down the rules on a small example first. Integer to Roman also builds an output string from a fixed, repeating pattern. Spiral matrix traversal is a close cousin that walks a grid with turning rules.

Natively for practice

Pattern-on-paper problems are hard to rehearse alone, because nobody stops you when the drawing is wrong. In a practice session on Mac or Windows, Natively can read the prompt from a screenshot, walk through a small layout with you, and check the cycle formula against your example. Its transcript lets you hear afterwards whether you named the one-row case before or after writing the loop.

Questions people ask

How do you solve Zigzag Conversion?

Keep one buffer per row and a current row that moves down and up. Append each character to the current row, flip direction on the top and bottom rows, then join the rows in order.

What is the cycle length in Zigzag Conversion?

2 * (numRows - 1). Within each cycle, row r takes the character at offset r, and rows strictly between the top and bottom also take the one at offset cycle - r.

What happens when numRows is 1 in Zigzag Conversion?

The text comes back unchanged. Return it early, because the cycle length would be 0 and the direction logic would break.

What is the time complexity of Zigzag Conversion?

O(n) for both the row-buffer and the index-arithmetic versions. Drawing a full grid is O(numRows * n) in time and memory.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP