Zigzag Conversion
Medium· simulation
Problem
Write the characters of a string down and up across a given number of rows in a zigzag pattern, then read the rows from top to bottom and concatenate them. Return that concatenated string.
Examples
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Row 0 gets P A H N, row 1 gets A P L S I I G, row 2 gets Y I R.
Input: s = "ABCDE", numRows = 4
Output: "ABCED"
Constraints
- • 1 <= s.length <= 1000
- • 1 <= numRows <= 1000
Hints & approach
Hint 1
You do not need a 2D grid; each row can be a separate buffer.
Hint 2
Track the current row and a direction that flips at the top and bottom rows.
Approachtry the hints first
If numRows is 1, return the string unchanged. Otherwise keep one string builder per row, a current row index and a direction (+1 or -1). Append each character to the current row, flip the direction when you hit row 0 or the last row, and step the row index. Joining the row builders in order gives the answer.
Time O(n) · Space O(n)