54. Spiral Matrix
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to traverse a given m x n 2D matrix in a spiral pattern. The traversal starts at the top-left corner, moves right across the first row, then down the last column, then left across the bottom row, then up the first column, and so on, spiraling inwards until all elements are visited. The goal is to return a 1D list containing all matrix elements in this specific order.
Solution
Spiral Matrix in Python
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
# Handle empty or invalid matrix
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
result = []
left, right, top, bottom = 0, n - 1, 0, m - 1
while left <= right and top <= bottom:
# Traverse Right: from left to right on the top row
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1 # Move the top boundary down
# Traverse Down: from top to bottom on the right column
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1 # Move the right boundary left
# Check if there's still a valid row to traverse
# This is important for non-square matrices (e.g., single column)
if top <= bottom:
# Traverse Left: from right to left on the bottom row
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1 # Move the bottom boundary up
# Check if there's still a valid column to traverse
# This is important for non-square matrices (e.g., single row)
if left <= right:
# Traverse Up: from bottom to top on the left column
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1 # Move the left boundary right
return result
Spiral Matrix in Java
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
// Handle empty or invalid matrix
if (matrix == null || matrix.length == 0) {
return result;
}
int m = matrix.length;
int n = matrix[0].length;
int top = 0, bottom = m - 1;
int left = 0, right = n - 1;
while (top <= bottom && left <= right) {
// Traverse Right: from left to right on the top row
for (int i = left; i <= right; i++) {
result.add(matrix[top][i]);
}
top++; // Move the top boundary down
// Traverse Down: from top to bottom on the right column
for (int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--; // Move the right boundary left
// Check if there's still a valid row to traverse
if (top <= bottom) {
// Traverse Left: from right to left on the bottom row
for (int i = right; i >= left; i--) {
result.add(matrix[bottom][i]);
}
bottom--; // Move the bottom boundary up
}
// Check if there's still a valid column to traverse
if (left <= right) {
// Traverse Up: from bottom to top on the left column
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++; // Move the left boundary right
}
}
return result;
}
}
Spiral Matrix in C++
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
// Handle empty or invalid matrix
if (matrix.empty() || matrix[0].empty()) {
return {};
}
int m = matrix.size();
int n = matrix[0].size();
vector<int> result;
// Reserve space to avoid reallocations
result.reserve(m * n);
int top = 0, bottom = m - 1;
int left = 0, right = n - 1;
while (top <= bottom && left <= right) {
// Traverse Right: from left to right on the top row
for (int i = left; i <= right; ++i) {
result.push_back(matrix[top][i]);
}
top++; // Move the top boundary down
// Traverse Down: from top to bottom on the right column
for (int i = top; i <= bottom; ++i) {
result.push_back(matrix[i][right]);
}
right--; // Move the right boundary left
// Check if there's still a row to traverse left
if (top <= bottom) {
// Traverse Left: from right to left on the bottom row
for (int i = right; i >= left; --i) {
result.push_back(matrix[bottom][i]);
}
bottom--; // Move the bottom boundary up
}
// Check if there's still a column to traverse up
if (left <= right) {
// Traverse Up: from bottom to top on the left column
for (int i = bottom; i >= top; --i) {
result.push_back(matrix[i][left]);
}
left++; // Move the left boundary right
}
}
return result;
}
};
Spiral Matrix in TypeScript
function spiralOrder(matrix: number[][]): number[] {
// Handle empty or invalid matrix
if (!matrix || matrix.length === 0 || matrix[0].length === 0) {
return [];
}
const m = matrix.length;
const n = matrix[0].length;
const result: number[] = [];
let top = 0, bottom = m - 1;
let left = 0, right = n - 1;
while (top <= bottom && left <= right) {
// Traverse Right: from left to right on the top row
for (let i = left; i <= right; i++) {
result.push(matrix[top][i]);
}
top++; // Move the top boundary down
// Traverse Down: from top to bottom on the right column
for (let i = top; i <= bottom; i++) {
result.push(matrix[i][right]);
}
right--; // Move the right boundary left
// Check if there's still a valid row to traverse
if (top <= bottom) {
// Traverse Left: from right to left on the bottom row
for (let i = right; i >= left; i--) {
result.push(matrix[bottom][i]);
}
bottom--; // Move the bottom boundary up
}
// Check if there's still a valid column to traverse
if (left <= right) {
// Traverse Up: from bottom to top on the left column
for (let i = bottom; i >= top; i--) {
result.push(matrix[i][left]);
}
left++; // Move the left boundary right
}
}
return result;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.