16. Spiral Matrix
mediumAsked at PostmanReturn all elements of an m x n matrix in spiral order.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given an m x n matrix, return all elements of the matrix in spiral order, starting at the top-left and walking clockwise.
Constraints
1 <= m, n <= 10-100 <= matrix[i][j] <= 100
Examples
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]Approaches
1. Visited matrix
Track visited cells in a parallel boolean matrix and turn when blocked or out of bounds.
- Time
- O(mn)
- Space
- O(mn)
// step in current direction; if next cell visited or OOB, turn rightTradeoff:
2. Layer shrinking
Maintain top, bottom, left, right boundaries; walk one edge, then shrink that boundary; stop when they cross.
- Time
- O(mn)
- Space
- O(1)
function spiral(m) {
const out = [];
let t = 0, b = m.length - 1, l = 0, r = m[0].length - 1;
while (t <= b && l <= r) {
for (let j = l; j <= r; j++) out.push(m[t][j]); t++;
for (let i = t; i <= b; i++) out.push(m[i][r]); r--;
if (t <= b) { for (let j = r; j >= l; j--) out.push(m[b][j]); b--; }
if (l <= r) { for (let i = b; i >= t; i--) out.push(m[i][l]); l++; }
}
return out;
}Tradeoff:
Postman-specific tips
Postman expects clean boundary tracking — they ship a UI grid editor for API examples, and bookkeeping errors map directly to off-by-one bugs in cell selection.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
More Postman coding interview questions
- 1. Two Sum
- 2. Valid Parentheses
- 3. Merge Two Sorted Lists
- 4. Best Time to Buy and Sell Stock
- 5. Reverse Linked List
- 6. Contains Duplicate
- 7. Valid Anagram
- 8. Valid Palindrome