20. Spiral Matrix
mediumAsked at UnityTraverse an m×n matrix in spiral order — the same UV unwrapping traversal Unity uses to pack a grid of texture tiles into a single atlas in a predictable, cache-friendly sequence.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an m x n matrix, return all elements of the matrix in spiral order (clockwise from the top-left).
Constraints
m == matrix.lengthn == matrix[i].length1 <= 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. Direction vector cycling
Maintain a direction array [right, down, left, up]. Walk until out-of-bounds or visited; turn clockwise. Use a visited set.
- Time
- O(m*n)
- Space
- O(m*n)
function spiralOrder(matrix) {
const m = matrix.length, n = matrix[0].length;
const dirs = [[0,1],[1,0],[0,-1],[-1,0]];
const seen = Array.from({length:m}, () => new Array(n).fill(false));
const res = [];
let r = 0, c = 0, d = 0;
for (let i = 0; i < m * n; i++) {
res.push(matrix[r][c]);
seen[r][c] = true;
const nr = r + dirs[d][0], nc = c + dirs[d][1];
if (nr < 0 || nr >= m || nc < 0 || nc >= n || seen[nr][nc]) d = (d + 1) % 4;
r += dirs[d][0];
c += dirs[d][1];
}
return res;
}Tradeoff:
2. Layer shrinking (four-pointer)
Track top/bottom/left/right boundaries. Peel the outermost layer each iteration, shrinking boundaries inward. O(1) extra space.
- Time
- O(m*n)
- Space
- O(1)
function spiralOrder(matrix) {
const res = [];
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++) res.push(matrix[top][c]);
top++;
for (let r = top; r <= bottom; r++) res.push(matrix[r][right]);
right--;
if (top <= bottom) {
for (let c = right; c >= left; c--) res.push(matrix[bottom][c]);
bottom--;
}
if (left <= right) {
for (let r = bottom; r >= top; r--) res.push(matrix[r][left]);
left++;
}
}
return res;
}Tradeoff:
Unity-specific tips
Unity interviewers look for spatial reasoning — describe the four-pointer approach as shrinking the tile region inward after each pass, mirroring how an atlas-packer reserves a border and moves inward. Draw the boundaries on a whiteboard before coding.
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 Unity interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →