1124. Snake Row Reader
A label printer sweeps across a sheet of m x n stickers in a back-and-forth pattern: it prints row 0 from left to right, then drops down and prints row 1 from right to left, then row 2 from left to right again, and so on, alternating on every row.
Given the integer grid grid, return all m*n values in the order the printer reads them. Even-numbered rows (0-based) are read left to right and odd-numbered rows right to left, with no value skipped or repeated.
Constraints: 1 <= m, n <= 50 and -10^4 <= grid[i][j] <= 10^4. Walking the rows once and choosing the direction by the parity of the row index gives O(m*n) time and O(1) extra space beyond the output.
Example 1
- Input:
- grid = [[1,2,3],[4,5,6],[7,8,9]]
- Output:
- [1,2,3,6,5,4,7,8,9]
- Explanation:
Row 0 is read left to right, row 1 right to left and row 2 left to right: 1 2 3 6 5 4 7 8 9.
Example 2
- Input:
- grid = [[10,20],[30,40],[50,60],[70,80]]
- Output:
- [10,20,40,30,50,60,80,70]
- Explanation:
Rows 1 and 3 are reversed, so the order is 10 20 40 30 50 60 80 70.
Constraints
1 ≤ m, n ≤ 50
-104 ≤ grid[i][j] ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(m*n)
- Space
- O(1)