medium Spiral Matrix
Problem Statement
Given a 2D matrix of size m x n, return the 1D array containing all elements of matrix in spiral order.
Examples
Example 1:
- Input: matrix =
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
- Expected Output:
[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10] - Justification: We have traversed the matrix in the spiral order.
Example 2:
- Input: matrix =
[[10,20,30],
[40,50,60],
[70,80,90]]
- Expected Output:
[10,20,30,60,90,80,70,40,50] - Justification: The traversal starts at the top-left, moves right to the end of the row, then down the right column, then left along the bottom row, up the left column, and finally captures the center.
Example 3:
- Input: matrix =
[[1,2],
[3,4],
[5,6]]
- Expected Output:
[1,2,4,6,5,3] - Justification: The traversal starts at the top-left, moves right, then down through the right column, and finally moves up the left column.
Constraints:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
Try it yourself
Try solving this question here:
✅ Solution Spiral Matrix
Problem Statement
Given a 2D matrix of size m x n, return the 1D array containing all elements of matrix in spiral order.
Examples
Example 1:
- Input: matrix =
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
- Expected Output:
[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10] - Justification: We have traversed the matrix in the spiral order.
Example 2:
- Input: matrix =
[[10,20,30],
[40,50,60],
[70,80,90]]
- Expected Output:
[10,20,30,60,90,80,70,40,50] - Justification: The traversal starts at the top-left, moves right to the end of the row, then down the right column, then left along the bottom row, up the left column, and finally captures the center.
Example 3:
- Input: matrix =
[[1,2],
[3,4],
[5,6]]
- Expected Output:
[1,2,4,6,5,3] - Justification: The traversal starts at the top-left, moves right, then down through the right column, and finally moves up the left column.
Constraints:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
Solution
To solve this problem, we employ a systematic approach to traverse the matrix in layers, starting from the outermost layer and gradually moving towards the inner layers. We maintain four pointers to mark the boundaries of the current layer: top, bottom, left, and right. Initially, these pointers are set to the boundaries of the matrix. In each iteration, we traverse the current layer in a spiral order: from left to right, top to bottom, right to left, and bottom to top, adjusting the boundary pointers accordingly after each direction of traversal. This approach ensures that we visit each element exactly once, maintaining the spiral order.
This method is effective because it clearly defines the traversal order and boundaries, preventing overlaps or missed elements. By systematically shrinking the traversal area and moving inward, we ensure complete coverage of the matrix in a spiral pattern. This logical progression mirrors the spiral traversal requirement, making it a natural fit for solving the problem.
Step-by-step Algorithm
- Initialize four pointers:
top = 0,bottom = matrix.length - 1,left = 0,right = matrix[0].length - 1. - Create an empty list
resultto store the spiral order. - While
(top <= bottom && left <= right):- Traverse from
lefttorightat thetoprow. After traversing, incrementtoppointer. - Traverse from
toptobottomat therightcolumn. After traversing, decrementrightpointer. - If
(top <= bottom), traverse fromrighttoleftat thebottomrow. After traversing, decrementbottompointer. - If
(left <= right), traverse frombottomtotopat theleftcolumn. After traversing, incrementleftpointer.
- Traverse from
- Return the
resultlist containing the elements in spiral order.
Algorithm Walkthrough
-
Initialize Boundary Pointers and Result Container:
- Top = 0 (index of the first row)
- Bottom = 3 (index of the last row)
- Left = 0 (index of the first column)
- Right = 3 (index of the last column)
- Result = [] (an empty list to store the spiral order)
-
First Outer Layer Traversal:
- Traverse from Left to Right along the Top row:
- Add elements 1, 2, 3, and 4 to Result.
- Increment Top to 1 (moving the top boundary down to exclude the traversed row).
- Traverse from Top to Bottom along the Right column:
- Add elements 8, 12, and 16 to Result.
- Decrement Right to 2 (moving the right boundary left to exclude the traversed column).
- Since Top ≤ Bottom, traverse from Right to Left along the Bottom row:
- Add elements 15, 14, and 13 to Result.
- Decrement Bottom to 2 (moving the bottom boundary up to exclude the traversed row).
- Since Left ≤ Right, traverse from Bottom to Top along the Left column:
- Add elements 9 and 5 to Result.
- Increment Left to 1 (moving the left boundary right to exclude the traversed column).
- Traverse from Left to Right along the Top row:
-
Second Inner Layer Traversal:
- Now, the pointers are adjusted to: Top = 1, Bottom = 2, Left = 1, Right = 2.
- Traverse from Left to Right along the new Top row (which is the second row now):
- Add elements 6 and 7 to Result.
- Increment Top to 2.
- Traverse from Top to Bottom along the Right column:
- Add element 11 in the results.
- Decrement Right to 1 (moving the right boundary left to exclude the traversed column).
- Since Top ≤ Bottom, traverse from Right to Left along the Bottom row:
- Add element 10 to Result.
- Decrement Bottom to 1 (moving the bottom boundary up to exclude the traversed row).
- Stop traversal as
top > bottom, andleft > right.
-
Final Result Compilation:
- After completing the spiral traversal correctly, the Result list now contains:
[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10] - This sequence correctly represents the spiral order traversal of the given matrix.
- After completing the spiral traversal correctly, the Result list now contains:
Code
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
// Validate input
if (matrix == null || matrix.length == 0) return result;
// Initialize boundary pointers
int top = 0, bottom = matrix.length - 1, left = 0, right =
matrix[0].length - 1;
// Traverse the matrix in a spiral order
while (top <= bottom && left <= right) {
// Traverse from left to right
for (int i = left; i <= right; i++) result.add(matrix[top][i]);
top++;
// Traverse from top to bottom
for (int i = top; i <= bottom; i++) result.add(matrix[i][right]);
right--;
// Traverse from right to left if top <= bottom
if (top <= bottom) {
for (int i = right; i >= left; i--) result.add(matrix[bottom][i]);
bottom--;
}
// Traverse from bottom to top if left <= right
if (left <= right) {
for (int i = bottom; i >= top; i--) result.add(matrix[i][left]);
left++;
}
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Example 1
int[][] matrix1 = { { 10, 20, 30 }, { 40, 50, 60 }, { 70, 80, 90 } };
System.out.println(sol.spiralOrder(matrix1));
// Example 2
int[][] matrix2 = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
System.out.println(sol.spiralOrder(matrix2));
// Example 3 (Revised)
int[][] matrix3 = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 },
};
System.out.println(sol.spiralOrder(matrix3));
}
}
Complexity Analysis
Time Complexity
, where m * nis the total number of elements in the matrix. Each element is visited exactly once, making the time complexity linear in terms of the number of elements in the matrix.
Space Complexity
, disregarding the output array. The algorithm uses a constant amount of space for the pointers (top, bottom, left, right) and the result list's space is not considered part of the algorithm's space complexity as it is required for the output. - If we consider the output space, then the space complexity is
, where m * nis the total number of elements in the matrix.
🤖 Don't fully get this? Learn it with Claude
Stuck on Spiral Matrix? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Spiral Matrix** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Spiral Matrix** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Spiral Matrix**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Spiral Matrix**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.