6. Zigzag Conversion
Given a string s and an integer numRows, write the characters of s in a zigzag pattern across numRows rows, then read the grid back one full row at a time and return the resulting string. This is the classic LeetCode #6 ("Zigzag Conversion").
Imagine writing the string downward across the rows. When you reach the bottom row you turn and move diagonally back up toward the top row, when you reach the top row you turn and go straight down again. You keep bouncing between the top and bottom rows until the whole string is placed.
For example, s = "PAYPALISHIRING" with numRows = 3 is laid out like this:
P A H N A P L S I I G Y I R
Reading row by row gives "PAHNAPLSIIGYIR".
You receive the string s and the integer numRows, and you must return the row-by-row concatenation. When numRows is 1 (or is at least the length of s) there is no zigzag and the answer is simply s unchanged.
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Explanation: Laid out in 3 rows the letters form the zigzag P..A..H..N / APLSIIG / Y..I..R, reading each row in turn yields PAHNAPLSIIGYIR.
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation: With 4 rows the diagonals are taller, so the same string reads back as PINALSIGYAHRPI.
Example 3:
Input: s = "A", numRows = 1
Output: "A"
Explanation: A single row means no zigzag at all, so the string is returned unchanged.
Constraints:
- 1 ≤ s.length ≤ 1000
- s consists of English letters (lower-case and upper-case), ',' and '.'.
- 1 ≤ numRows ≤ 1000
Hints:
You don't actually need a 2D grid. Keep one string buffer per row and append each character to the correct row as you scan s left to right.
Track which row you're on and a direction (+1 going down, -1 going up). Flip the direction whenever you hit the top row (index 0) or the bottom row (index numRows - 1).
Handle numRows == 1 as a special case: there is only one row, so the answer is just s.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: s = "PAYPALISHIRING", numRows = 3
Expected output: "PAHNAPLSIIGYIR"