AAlgoLoopSpaced repetition for LeetCode
MEDIUMMatrix / GridLeetCode ↗

Spiral Matrix

The key idea

Maintain four shrinking boundaries — top, bottom, left, right. Walk one edge at a time in the order right, down, left, up, and pull that boundary inward after each edge. The top <= bottom and left <= right guards stop you before the rings overlap, which also handles non-square shapes cleanly.

Problem

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

Starting from the top-left corner, traverse the elements in a clockwise spiral: go across the top row, down the right side, back across the bottom row, up the left side, then continue inward ring by ring until every cell has been visited exactly once. Each value of matrix[i][j] appears in the output exactly once, and the returned list has length m * n.

Constraints

Examples

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

Complexity

Time: O(m*n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Matrix / Grid problems