Skip to content
Problem 6 · LeetCode 6(opens in a new tab)

Zigzag Conversion

MediumStrings

Write the string s in a zigzag over numRows rows: put the first letter in the top row and go straight down one row per letter. At the bottom row, turn and go diagonally back up, one row per letter, until you reach the top. Then go down again, and so on until the letters run out.

Return the string you get by reading the zigzag one row at a time, from the top row to the bottom row, left to right within each row.

Example 1

Input:  s = "WATERMELON", numRows = 3
Output: "WROAEMLNTE"
Why:    rows are W R O, A E M L N and T E
2 more examples and the constraints

Example 2

Input:  s = "WATERMELON", numRows = 4
Output: "WEAMLTROEN"
Why:    rows are W E, A M L, T R O and E N

Example 3

Input:  s = "Hi.", numRows = 1
Output: "Hi."
Why:    one row is the string itself

Constraints

  • 1 ≤ length of s ≤ 1,000
  • s holds English letters (either case), commas and full stops
  • 1 ≤ numRows ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Walk the zigzag into rowsO(n)
  2. Read each row by its cycleO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 lettersVerdict
Walk the zigzag into rowsO(n)
Passes; easiest to get right
Read each row by its cycleO(n)
Best; writes the answer directly

n = length of s. Both touch each letter a constant number of times.

Edge cases to test

  • One row. "Hi." with 1 row is unchanged; without a guard the cycle is 0 and the loop never moves.
  • More rows than letters. "abc" with 5 rows is one straight column, so the answer is "abc".
  • Two rows. There are no middle rows: even indices, then odd ones. "abcde" gives "acebd".
  • Punctuation and case. Commas, full stops and capitals are letters like any other; nothing is skipped.

Common mistakes

  • Forgetting the numRows = 1 case, so the direction flips on every letter or the cycle is 0.
  • Adding the way-up letter in the top or bottom row too, which counts some letters twice.
  • Building a full 2D grid of numRows × n cells, which wastes space and is easy to index wrongly.

How to talk through it

  1. 1Clarify. What if there is one row, or more rows than letters? Are spaces or punctuation special?
  2. 2Simulate first. One bucket per row and a direction that flips at the top and bottom. Say it is O(n).
  3. 3Find the period. Down and back up takes 2·numRows − 2 letters, so the pattern repeats.
  4. 4Read rows directly. Top and bottom rows take every cycle-th letter; middle rows add one more per cycle.
  5. 5Test out loud. Run one row, two rows and more rows than letters.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?