DSA · Arrays & Matrix · #168
Spiral Matrix
Module 81 · difficulty 3/5·⏱ 30:00starts on first keystroke
Given an `m x n` matrix, return all of its elements in **spiral order** — starting at the top-left, moving right, then down, then left, then up, spiraling inward until every cell is visited. Implement `spiralOrder(matrix)` which returns the elements as a single array in the order they are visited.
Examples
matrix = [[1,2,3],[4,5,6],[7,8,9]]→[1,2,3,6,9,8,7,4,5]— Right across the top, down the right edge, left across the bottom, up the left edge, then the center.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]— Non-square matrix; the inner ring is a single horizontal run [5,6,7].matrix = [[7]]→[7]— A single cell.
Constraints
- · m == matrix.length
- · n == matrix[i].length
- · 1 <= m, n <= 10
- · -100 <= matrix[i][j] <= 100
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.