Traverse an m x n 2D matrix in spiral clockwise order.
Problem Statement
Examples
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Explanation: Combining the input according to Print the matrix in spiral manner logic yields [1, 2, 3, 6, 9, 8, 7, 4, 5].
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]
Explanation: Combining the input according to Print the matrix in spiral manner logic yields [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7].
Complexity
Time Complexity: O(M * N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
Traverse in concentric rectangular layers. By keeping four boundaries (top, bottom, left, right), we traverse each edge in order and contract the boundary inwards until all elements are recorded.
Step-by-Step Approach
- Set
top = 0, bottom = m - 1, left = 0, right = n - 1. - Traverse
lefttorightacrosstop, thentop++. - Traverse
toptobottomdownright, thenright--. - If
top <= bottom, traverserighttoleftacrossbottom, thenbottom--. - If
left <= right, traversebottomtotopupleft, thenleft++. - Return accumulated
result.
Optimal Implementation (JavaScript)
function spiralOrder(matrix) {
if (!matrix.length) return [];
const result = [];
let top = 0, bottom = matrix.length - 1;
let left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let c = left; c <= right; c++) result.push(matrix[top][c]);
top++;
for (let r = top; r <= bottom; r++) result.push(matrix[r][right]);
right--;
if (top <= bottom) {
for (let c = right; c >= left; c--) result.push(matrix[bottom][c]);
bottom--;
}
if (left <= right) {
for (let r = bottom; r >= top; r--) result.push(matrix[r][left]);
left++;
}
}
return result;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Single row matrix.
- Single column matrix.
- Non-square matrices (m != n).