Spiral Matrix Traversal in DSA Java - Time & Space Complexity
We want to understand how the time needed to traverse a matrix in a spiral grows as the matrix size increases.
How does the number of steps change when the matrix gets bigger?
Analyze the time complexity of the following code snippet.
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) result.add(matrix[top][i]);
top++;
for (int i = top; i <= bottom; i++) result.add(matrix[i][right]);
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) result.add(matrix[bottom][i]);
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) result.add(matrix[i][left]);
left++;
}
}
return result;
}
This code visits every element of a 2D matrix in a spiral order, starting from the top-left corner and moving inward.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each element of the matrix exactly once.
- How many times: Each element is visited once during the spiral traversal loops.
As the matrix size grows, the number of elements to visit grows with the total number of cells.
| Input Size (n x n) | Approx. Operations (visits) |
|---|---|
| 10 x 10 | 100 |
| 100 x 100 | 10,000 |
| 1000 x 1000 | 1,000,000 |
Pattern observation: The operations grow proportionally to the total number of elements, so doubling the size of one side multiplies the work by four.
Time Complexity: O(n * m)
This means the time grows directly with the total number of elements in the matrix, visiting each once.
[X] Wrong: "The spiral traversal has nested loops making it O(n² * m²) or worse."
[OK] Correct: Although there are loops inside loops, each element is visited only once, so the total work is just proportional to the number of elements, not their square.
Understanding how to analyze traversal of 2D structures like matrices is a key skill. It shows you can reason about loops and data size clearly, which is valuable in many coding problems.
"What if the matrix was not rectangular but jagged (rows of different lengths)? How would the time complexity change?"
Practice
Spiral Matrix Traversal?Solution
Step 1: Understand traversal pattern
Spiral traversal means moving around the edges of the matrix and gradually moving inward in a circular way.Step 2: Compare options
Only Traverse the matrix in a circular pattern from outer to inner layers describes moving in a circular pattern from outer to inner layers, which matches spiral traversal.Final Answer:
Traverse the matrix in a circular pattern from outer to inner layers -> Option AQuick Check:
Spiral traversal = circular outer to inner [OK]
- Confusing spiral with row-wise traversal
- Thinking spiral means diagonal only
- Mixing column-wise with spiral
int[][] matrix?Solution
Step 1: Identify matrix dimensions
For a 2D array, rows = matrix.length, columns = matrix[0].length.Step 2: Set boundaries correctly
Top and left start at 0, bottom is last row index (length-1), right is last column index (length-1). int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1; matches this.Final Answer:
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1; -> Option BQuick Check:
Boundaries start at 0 and end at length-1 [OK]
- Using 1-based indices instead of 0-based
- Swapping rows and columns in boundaries
- Setting bottom or right greater than max index
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int top = 0, bottom = 2, left = 0, right = 2;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) System.out.print(matrix[top][i] + " ");
top++;
for (int i = top; i <= bottom; i++) System.out.print(matrix[i][right] + " ");
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) System.out.print(matrix[bottom][i] + " ");
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) System.out.print(matrix[i][left] + " ");
left++;
}
}Solution
Step 1: Trace first outer layer
Top row: 1 2 3, right column down: 6 9, bottom row left: 8 7, left column up: 4Step 2: Trace inner layer
Now top=1, bottom=1, left=1, right=1, print center element: 5Final Answer:
1 2 3 6 9 8 7 4 5 -> Option CQuick Check:
Spiral order matches 1 2 3 6 9 8 7 4 5 [OK]
- Printing rows or columns in wrong order
- Missing center element in odd-sized matrix
- Not updating boundaries correctly
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top < bottom && left < right) {
for (int i = left; i <= right; i++) System.out.print(matrix[top][i] + " ");
top++;
for (int i = top; i <= bottom; i++) System.out.print(matrix[i][right] + " ");
right--;
for (int i = right; i >= left; i--) System.out.print(matrix[bottom][i] + " ");
bottom--;
for (int i = bottom; i >= top; i--) System.out.print(matrix[i][left] + " ");
left++;
}Solution
Step 1: Analyze while loop condition
Using < excludes the case when top == bottom or left == right, missing last layer in odd-sized matrices.Step 2: Correct condition to include all layers
Changing to <= ensures the center or last layer is processed.Final Answer:
The while condition should use <= instead of < to include all layers -> Option AQuick Check:
Use <= in while to cover all layers [OK]
- Using < excludes center element in odd matrices
- Not updating boundaries after each loop
- Missing if checks for inner loops
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};What is the spiral traversal output?
Solution
Step 1: Traverse top row left to right
Print 1 2 3 4Step 2: Traverse right column top to bottom
Print 8 12Step 3: Traverse bottom row right to left
Print 11 10 9Step 4: Traverse left column bottom to top
Print 5Step 5: Traverse inner row left to right
Print 6 7Final Answer:
1 2 3 4 8 12 11 10 9 5 6 7 -> Option DQuick Check:
Follow edges inward for rectangular matrix [OK]
- Mixing order of inner elements
- Skipping last inner row
- Confusing left column traversal direction
Ready to prove it?
Pass the test and this pattern moves unknown
