Skip to content

Spiral Matrix

Medium Day 10 • Striver Blind 75

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

  • Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
  • Output: [1,2,3,6,9,8,7,4,5]

Constraints:

  • 1 <= m, n <= 10

4 boundaries (top, bottom, left, right) narrowed after each traversal leg.

Matrix Boundary Shrinking


📊 Step-by-Step Execution (Mermaid Diagram)

Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”
graph TD
Start["Input Data"] --> Process["Process Element by Element"]
Process --> Lookup{"Hash Map / Set Lookup"}
Lookup -- "Match Found" --> Return["Return Indices / Result"]
Lookup -- "No Match" --> Store["Store in Map / Set"]
Store --> Process

function spiralOrder(matrix) {
const res = [];
let top = 0, bottom = matrix.length - 1, 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;
}
  • Time Complexity: O(m*n)
  • Space Complexity: O(1)
  • Explanation: Boundary contraction.

function spiralOrder(matrix) {
const res = [];
let top = 0, bottom = matrix.length - 1, 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;
}
  • Time Complexity: O(m*n)
  • Space Complexity: O(1)
  • Explanation: Layer-by-layer boundary shrinking traversal.

  1. Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
  2. Iterate & Evaluate: Process the input according to the boundary conditions.
  3. Update & Return: Compute the optimal answer and return early or at termination.

Traverse right, down, left, up while shrinking top/bottom/left/right boundary bounds.


  1. Maintain top, bottom, left, right boundaries.

👉 Solve this problem interactively in the DSA Lab