15% off all plans & roadmaps Use code
See plansLeetCode 54 · Solution & editorial
Given an m x n matrix, return all elements of the matrix in spiral order.
Spiral Matrix is a Array/Matrix Manipulation Patterns problem, in the Spiral Traversal subpattern. The pattern covers in-place operations, hashing, prefix sums, spiral traversal, and cyclic sort
Master spiral traversal pattern for 2D matrices. Learn to traverse matrices in spiral order for interview problems.
The reference solution runs in O(m * n) time and O(1) space.
Spiral Matrix has been reported in interviews at Microsoft, Apple, Intuit, Facebook, Google, Amazon, ByteDance, Expedia.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Spiral Matrix is a Array/Matrix Manipulation Patterns problem, in the Spiral Traversal subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.