Traverse a matrix in spiral order
Return the clockwise spiral traversal of a rectangular matrix, starting at its top-left cell. Empty matrices are allowed. Inputs are valid JSON and must not be modified unless the algorithm uses a local copy. This exercise probes typed data modeling, boundary handling, and algorithm selection.
Input
One JSON value: number[][]. See the sample for its exact shape.
Output
One compact JSON value of type number[]. Strings include JSON quotes; arrays preserve the specified order.
Constraints
Array/string lengths are 0 to 10000 unless stated otherwise. Numbers are integers in [-1000000,1000000]; all computed results fit the safe integer range.
Example
Input
[[1,2,3],[4,5,6],[7,8,9]]
Output
[1,2,3,6,9,8,7,4,5]
Example 2 input
[[1,2,3],[4,5,6]]
Output
[1,2,3,6,5,4]
Checks a boundary or contrasting case beyond the public examples.
Public test cases (2)
Input
[[1,2,3],[4,5,6],[7,8,9]]
Expected output
[1,2,3,6,9,8,7,4,5]
Input
[]
Expected output
[]
Hints (2)
- Start with the required output order and the empty-input behavior.
- Shrink four boundaries after traversing their edges
Target complexity: time O(rows*cols) · space O(rows*cols)
