All Blind 75 questions

Spiral Matrix

FreeMatricesMedium69 of 75

The problem

Return the values of a rectangular matrix in clockwise spiral order, starting at the top-left.

Example

[[1, 2, 3], [4, 5, 6]] → [1, 2, 3, 6, 5, 4]

Need a hint?

Shrink four boundaries after traversing each outer layer.

Write pseudocode, trace the example, or note an edge case. This scratchpad does not run code.

Notes stay in this browser when storage is available.

Read the solution approach

Maintain top, bottom, left, and right bounds. Traverse the top row, right column, bottom row, and left column, tightening each bound. Recheck the bounds before the bottom and left passes so a single remaining row or column is not duplicated.

Complexity

O(mn) time and O(1) auxiliary space excluding output.

Before moving on, explain why the algorithm is correct and trace a boundary case without looking at the approach.