Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Spiral Matrix

mediummatrixsimulation

Problem

Given a grid of integers with m rows and n columns, return all of its elements in clockwise spiral order: start at the top-left corner, walk right along the top row, then down the right column, then left along the bottom row, then up the left column, and continue inward until every cell has been visited exactly once.

  • The grid has at most about a dozen rows and columns.
  • Cell values are small integers.

Examples

  • [[2,4,6],[8,10,12],[14,16,18]] → [2,4,6,12,18,16,14,8,10].
  • [[1,2,3,4],[10,11,12,5],[9,8,7,6]] → [1,2,3,4,5,6,7,8,9,10,11,12]. After the outer ring, the inner "ring" is the single row 11,12, which must not be read twice.
  • [[9],[8],[7]] → [9,8,7]; a single column has only the "right" and "down" moves, and the "left" and "up" passes must be skipped.

Hints

  1. Keep four boundaries: top, bottom, left, right. Each full lap reads one row or column along each boundary and then shrinks that boundary.
  2. Where does the naive loop double-count? Think about what happens when only one row or one column remains in the middle.
  3. After reading the top row and right column, read the bottom row only if top <= bottom still holds, and the left column only if left <= right still holds.

Last reviewed 8 September 2026