Spiral Matrix
Medium · Matrices
Jump to codeReturn the values of a rectangular matrix in clockwise spiral order, starting at the top-left.
Examples
Example 1
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2
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]
Constraints
- 1 <= matrix.length, matrix[i].length <= 10
- -100 <= matrix[i][j] <= 100
Need a hint?
Shrink four boundaries after traversing each outer layer.
Asked in real interviews
Candidates reported versions of Spiral Matrix from these company interviews. Some company questions are locked and open with Premium or XP.
- Traverse a Matrix in Spiral OrderPinduoduo
- Clockwise Spiral Traversal of a Matrix With O(1) Extra Space and No MutationByteDance
- Traverse a Matrix in Clockwise Spiral OrderMicrosoft
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.
Python reference solution
def spiralOrder(matrix):
if not matrix or not matrix[0]:
return []
top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
answer = []
while top <= bottom and left <= right:
for col in range(left, right + 1):
answer.append(matrix[top][col])
top += 1
for row in range(top, bottom + 1):
answer.append(matrix[row][right])
right -= 1
if top <= bottom:
for col in range(right, left - 1, -1):
answer.append(matrix[bottom][col])
bottom -= 1
if left <= right:
for row in range(bottom, top - 1, -1):
answer.append(matrix[row][left])
left += 1
return answer
JavaScript solution
function spiralOrder(matrix) {
if (!matrix.length || !matrix[0].length) return [];
let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
const answer = [];
while (top <= bottom && left <= right) {
for (let col = left; col <= right; col++) answer.push(matrix[top][col]);
top++;
for (let row = top; row <= bottom; row++) answer.push(matrix[row][right]);
right--;
if (top <= bottom) {
for (let col = right; col >= left; col--) answer.push(matrix[bottom][col]);
bottom--;
}
if (left <= right) {
for (let row = bottom; row >= top; row--) answer.push(matrix[row][left]);
left++;
}
}
return answer;
}
Java solution
import java.util.*;
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return new int[0];
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
int[] answer = new int[matrix.length * matrix[0].length];
int i = 0;
while (top <= bottom && left <= right) {
for (int col = left; col <= right; col++) answer[i++] = matrix[top][col];
top++;
for (int row = top; row <= bottom; row++) answer[i++] = matrix[row][right];
right--;
if (top <= bottom) {
for (int col = right; col >= left; col--) answer[i++] = matrix[bottom][col];
bottom--;
}
if (left <= right) {
for (int row = bottom; row >= top; row--) answer[i++] = matrix[row][left];
left++;
}
}
return answer;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>> &matrix) {
if (matrix.empty() || matrix[0].empty()) return {};
int top = 0, bottom = matrix.size() - 1, left = 0, right = matrix[0].size() - 1;
vector<int> answer;
while (top <= bottom && left <= right) {
for (int col = left; col <= right; col++) answer.push_back(matrix[top][col]);
top++;
for (int row = top; row <= bottom; row++) answer.push_back(matrix[row][right]);
right--;
if (top <= bottom) {
for (int col = right; col >= left; col--) answer.push_back(matrix[bottom][col]);
bottom--;
}
if (left <= right) {
for (int row = bottom; row >= top; row--) answer.push_back(matrix[row][left]);
left++;
}
}
return answer;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 9 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
[
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 ]
[
[
[
1
]
]
][ 1 ]
[
[
[
1,
2,
3,
4
]
]
][ 1, 2, 3, 4 ]
[
[
[
1
],
[
2
],
[
3
],
[
4
]
]
][ 1, 2, 3, 4 ]
Drafts are saved per language in this browser when storage is available.