CodingNodes / Arrays & Hashing / Zigzag Conversion System design Space play · ←→ step · R restart

Problem

Write the string s in a zigzag over numRows rows: go down the rows one letter at a time, and when you hit the bottom row turn and go back up diagonally, then turn down again at the top.

After writing the whole string this way, read the rows from top to bottom, each from left to right, and join the letters into a single string. Return that string. For example, "ABCDE" over 2 rows is written as A C E on row 0 and B D on row 1, giving "ACEBD".

Constraints

  • 1 ≤ s.length ≤ 1000
  • s contains letters (a–z, A–Z), commas and periods
  • 1 ≤ numRows ≤ 1000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Each letter is appended to one row exactly once, then the rows are joined.

Space: The rows together hold all n letters.

Keep one string per row and a direction. Drop each letter into the current row, flip the direction when you reach the top or bottom row, and move one row. Finally join the rows from top to bottom.