Back to Practice
#0292

Spiral Matrix Order

MediumDSA28 min20 XP

Problem

Given a matrix, return its values in clockwise spiral order starting from the top-left corner.

Why This Matters

Spiral traversal trains careful boundary updates, a common source of off-by-one bugs.

Function Signature

def spiral_order(matrix):

Examples

Example 1
Inputmatrix = [[1,2,3],[4,5,6],[7,8,9]]
Output[1, 2, 3, 6, 9, 8, 7, 4, 5]

Walk top row, right column, bottom row reversed, left column reversed, then move inward.

Constraints

  • Return the exact requested value.
  • Handle edge cases cleanly.
  • Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Square matrix
Input3 by 3
Expected[1, 2, 3, 6, 9, 8, 7, 4, 5]

The center is visited last.

Rectangle matrix
Input3 by 4
Expected[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

Boundary checks avoid revisiting rows or columns.

Hidden Test Categories
single rowsingle columnempty matrix