Boundary traversal · Medium
A visualization tool reveals a rectangular matrix one outer ring at a time. It begins at the top-left corner and travels clockwise. Every cell must appear exactly once, including thin final rows or columns.
Return a flat array of all matrix values in clockwise spiral order without modifying the matrix.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "matrix": number[][] }.
Fields
- matrix is rectangular. Every row has the same length, including when the length is zero.
Output
Return value
- Start along the top row to the right, then down, left and up around each remaining ring.
- Return every cell once. An empty dimension returns [].
Constraints
- 0 <= rows, columns <= 1000; rows*columns <= 1000000.
- Values are integers in [-1000000000,1000000000].
Examples
Example 1
{
"matrix": [
[
1,
2,
3
],
[
4,
5,
6
]
]
}Returns
[
1,
2,
3,
6,
5,
4
]One rectangular ring.
Example 2
{
"matrix": [
[
1
],
[
2
],
[
3
]
]
}Returns
[
1,
2,
3
]Do not traverse the same column twice.
Required complexity
O(rows * columns) time and O(1) working space excluding output