Overview
Given an m × n matrix, return all elements in spiral order — starting from the top-left, moving right, then down, then left, then up, and repeating inward.
Constraints
1 <= m, n <= 10-100 <= matrix[i][j] <= 100- Return a flat array of all elements in spiral order.
Examples
spiralOrder([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]); // => [1, 2, 3, 6, 9, 8, 7, 4, 5]
spiralOrder([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ]); // => [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Solution
Reveal solution
function spiralOrder(matrix) {
const 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;
}Use four boundary pointers (top, bottom, left, right) and shrink them after each pass.
Resources
matrix-spiral-traversal.js
Matrix Spiral Traversal
mediumcodingAlgorithmsMatrix
Overview
Given an m × n matrix, return all elements in spiral order — starting from the top-left, moving right, then down, then left, then up, and repeating inward.
Constraints
1 <= m, n <= 10-100 <= matrix[i][j] <= 100- Return a flat array of all elements in spiral order.
Examples
spiralOrder([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]); // => [1, 2, 3, 6, 9, 8, 7, 4, 5]
spiralOrder([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ]); // => [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Solution
Reveal solution
function spiralOrder(matrix) {
const 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;
}Use four boundary pointers (top, bottom, left, right) and shrink them after each pass.
Resources
NameTopicDifficulty
103 of 103 problems