Spiral Matrix
Given an m x n matrix, return all elements of the matrix in spiral order — starting from the top-left corner, moving right across the top row, then down the right column, left across the bottom row, and up the left column, repeating inward.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Edge cases: A single row or single column matrix. An empty matrix should return [].
Sample Input
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Sample Output
[1,2,3,6,9,8,7,4,5]
Constraints
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
Test Cases
Case 1
Args: [[[1,2,3],[4,5,6],[7,8,9]]]
Expected: [1,2,3,6,9,8,7,4,5]
Topics
Approach: Layer-by-Layer Boundaries
Track four boundaries — top, bottom, left, right — and peel off one layer of the spiral per iteration. After each direction traversal, shrink the corresponding boundary and check whether you've crossed over.
function spiralOrder(matrix) {
const result = [];
if (!matrix.length) return result;
let top = 0, bottom = matrix.length - 1;
let left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++) result.push(matrix[top][i]);
top++;
for (let i = top; i <= bottom; i++) result.push(matrix[i][right]);
right--;
if (top <= bottom) {
for (let i = right; i >= left; i--) result.push(matrix[bottom][i]);
bottom--;
}
if (left <= right) {
for (let i = bottom; i >= top; i--) result.push(matrix[i][left]);
left++;
}
}
return result;
}
Time Complexity: O(m × n) — every element is visited once
Space Complexity: O(1) extra space (excluding the output array)
Saved in this browser only. Private to you.