Matrices
Medium

Spiral Matrix

Return all elements of the matrix in spiral order.
Problem Understanding

Given an m x n matrix, return all elements of the matrix in spiral order (Right -> Down -> Left -> Up).

Interactive Visualization
Step 1 / 1

Visualization data missing

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE
Strategy

We can simulate the spiral movement by defining boundaries (top, bottom, left, right):

  1. Move Right: Traverse from left to right. Increment top.
  2. Move Down: Traverse from top to bottom. Decrement right.
  3. Move Left: Traverse from right to left. Decrement bottom. (Check top <= bottom first)
  4. Move Up: Traverse from bottom to top. Increment left. (Check left <= right first)
  • Initialize top=0, bottom=rows-1, left=0, right=cols-1.

  • Loop while top <= bottom and left <= right.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep