19. Spiral Matrix
mediumAsked at MercadoLibreReturn all elements of a matrix in spiral order.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an m x n matrix, return all elements in spiral order, starting from the top-left and walking clockwise around the boundary, then peeling inward.
Constraints
1 <= m, n <= 10-100 <= matrix[i][j] <= 100
Examples
Example 1
matrix = [[1,2,3],[4,5,6],[7,8,9]][1,2,3,6,9,8,7,4,5]Example 2
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]][1,2,3,4,8,12,11,10,9,5,6,7]Approaches
1. Visited mark
Walk with direction vectors, marking cells visited.
- Time
- O(m*n)
- Space
- O(m*n)
const out = [], m = matrix.length, n = matrix[0].length, seen = Array.from({length:m}, () => new Array(n).fill(false));
const d = [[0,1],[1,0],[0,-1],[-1,0]];
let r = 0, c = 0, di = 0;
for (let k = 0; k < m*n; k++) {
out.push(matrix[r][c]); seen[r][c] = true;
const nr = r + d[di][0], nc = c + d[di][1];
if (nr < 0 || nr >= m || nc < 0 || nc >= n || seen[nr][nc]) { di = (di+1)%4; }
r += d[di][0]; c += d[di][1];
}
return out;Tradeoff:
2. Shrinking boundaries
Track top/bottom/left/right boundaries; peel one layer per loop iteration.
- Time
- O(m*n)
- Space
- O(1)
function spiralOrder(matrix) {
const out = [];
let top = 0, bot = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (top <= bot && left <= right) {
for (let c = left; c <= right; c++) out.push(matrix[top][c]);
top++;
for (let r = top; r <= bot; r++) out.push(matrix[r][right]);
right--;
if (top <= bot) for (let c = right; c >= left; c--) out.push(matrix[bot][c]);
bot--;
if (left <= right) for (let r = bot; r >= top; r--) out.push(matrix[r][left]);
left++;
}
return out;
}Tradeoff:
MercadoLibre-specific tips
MercadoLibre warehouse engineers use this to test boundary-shrink discipline — the same pattern they apply when walking aisles in a São Paulo fulfillment center to plan robot pick paths.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Spiral Matrix and other MercadoLibre interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →