Spiral Matrix

Peel layers in four-direction order, shrinking the active rectangle after each side.

Medium
Time O(m*n) Space O(1)
LeetCode
4 min read
matrix simulation

Problem#

Given an m x n matrix, return all elements in spiral order starting from the top-left, walking right → down → left → up, then inward.

Examples#

  • [[1,2,3],[4,5,6],[7,8,9]][1,2,3,6,9,8,7,4,5]
  • [[1,2,3,4],[5,6,7,8],[9,10,11,12]][1,2,3,4,8,12,11,10,9,5,6,7]

Constraints#

  • m == matrix.length, n == matrix[i].length, 1 <= m, n <= 10.

Approach#

Maintain four bounds: top, bottom, left, right. Repeatedly walk the top row left-to-right, right column top-to-bottom, bottom row right-to-left, and left column bottom-to-top. After each side, shrink the corresponding bound and check if the rectangle is still non-degenerate.

Solution#

Spiral Matrix
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
int top = 0, bottom = m - 1, left = 0, right = n - 1;
vector<int> ans;
ans.reserve(m * n);
while (top <= bottom && left <= right) {
for (int j = left; j <= right; ++j) ans.push_back(matrix[top][j]);
++top;
for (int i = top; i <= bottom; ++i) ans.push_back(matrix[i][right]);
--right;
if (top <= bottom) {
for (int j = right; j >= left; --j) ans.push_back(matrix[bottom][j]);
--bottom;
}
if (left <= right) {
for (int i = bottom; i >= top; --i) ans.push_back(matrix[i][left]);
++left;
}
}
return ans;
}
};

Editorial#

The two extra if guards after the bottom and left passes are vital when the matrix is non-square — once you’ve consumed one row or column, the next direction may overlap and double-add elements without the check.

Complexity#

  • Time: O(m*n).
  • Space: O(1) extra.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.