50. Spiral Matrix
mediumAsked at OlaReturn all elements of a 2D matrix in spiral order.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an m x n matrix, return all elements of the matrix in spiral order, starting from the top-left and going clockwise.
Constraints
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10
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. Mark visited
Walk in a direction; when a wall or visited cell appears, turn right.
- Time
- O(m*n)
- Space
- O(m*n)
// direction-step approach with visited[][] gridTradeoff:
2. Layered bounds
Track top/bottom/left/right bounds; walk each side and shrink the bound. O(m*n) without extra memory.
- 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 j = left; j <= right; j++) out.push(matrix[top][j]); top++;
for (let i = top; i <= bot; i++) out.push(matrix[i][right]); right--;
if (top <= bot) for (let j = right; j >= left; j--) out.push(matrix[bot][j]); bot--;
if (left <= right) for (let i = bot; i >= top; i--) out.push(matrix[i][left]); left++;
}
return out;
}Tradeoff:
Ola-specific tips
Ola interviewers like to see clean bound-tracking; tie it to scanning a 2D city-grid for high-demand cells in concentric layers.
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 Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →