Spiral Matrix Traversal in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to read all elements in a matrix in spiral order 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.
function spiralOrder(matrix: number[][]): number[] {
const result: number[] = [];
let top = 0, bottom = matrix.length - 1;
let left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++) result.push(matrix[top][i]);
top++;
for (let i = top; i <= bottom; i++) result.push(matrix[i][right]);
right--;
if (top <= bottom) {
for (let i = right; i >= left; i--) result.push(matrix[bottom][i]);
bottom--;
}
if (left <= right) {
for (let i = bottom; i >= top; i--) result.push(matrix[i][left]);
left++;
}
}
return result;
}
This code reads all elements of a matrix in a spiral order, moving layer by layer from outside to inside.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loops that traverse the matrix edges in each spiral layer.
- How many times: Each element of the matrix is visited exactly once as the loops move inward.
As the matrix size grows, the number of elements to visit grows too, and the loops cover all elements once.
| Input Size (n x n) | Approx. Operations |
|---|---|
| 10 x 10 | 100 |
| 100 x 100 | 10,000 |
| 1000 x 1000 | 1,000,000 |
Pattern observation: The operations grow roughly proportional to the total number of elements, so if the matrix size doubles, the operations roughly quadruple.
Time Complexity: O(m * n)
This means the time grows directly with the total number of elements in the matrix, visiting each element once.
[X] Wrong: "The loops inside loops mean the time is squared or worse, like O(n²) always."
[OK] Correct: Although there are nested loops, each element is visited only once in total, so the time grows linearly with the number of elements, not squared.
Understanding how to analyze traversal of 2D structures like matrices is a key skill that shows you can reason about loops and data size clearly.
"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 first, then moving inward layer by layer.Step 2: Compare options
Only Traverse the matrix in a circular pattern starting from the outer layer moving inward describes this circular, inward movement. Others describe linear or diagonal traversals.Final Answer:
Traverse the matrix in a circular pattern starting from the outer layer moving inward -> Option AQuick Check:
Spiral traversal = circular inward movement [OK]
- Confusing spiral with row-wise traversal
- Thinking spiral means diagonal only
- Ignoring inward movement after outer layer
Solution
Step 1: Identify correct boundary initialization
Top and left start at 0 (first row and column). Bottom and right are last indices, so length - 1.Step 2: Check options
let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1; correctly sets top=0, bottom=rows-1, left=0, right=cols-1. Others have off-by-one or negative values.Final Answer:
let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1; -> Option DQuick Check:
Boundaries start at 0 and end at length-1 [OK]
- Using length instead of length - 1 for boundaries
- Starting top or left at 1 instead of 0
- Using negative indices incorrectly
Solution
Step 1: Calculate total elements in matrix
Number of elements = rows x columns = 3 x 5 = 15.Step 2: Understand spiral traversal covers all elements
Spiral traversal visits every element exactly once, so all 15 elements are printed.Final Answer:
15 -> Option AQuick Check:
Total elements = rows x columns = 15 [OK]
- Confusing spiral length with perimeter
- Counting only outer layer elements
- Ignoring rectangular shape
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
function spiralOrder(matrix: number[][]): number[] {
const result: number[] = [];
let top = 0, bottom = matrix.length - 1;
let left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++) result.push(matrix[top][i]);
top++;
for (let i = top; i <= bottom; i++) result.push(matrix[i][right]);
right--;
if (top <= bottom) {
for (let i = right; i >= left; i--) result.push(matrix[bottom][i]);
bottom--;
}
if (left <= right) {
for (let i = bottom; i >= top; i--) result.push(matrix[i][left]);
left++;
}
}
return result;
}
console.log(spiralOrder(matrix));Solution
Step 1: Trace the spiral traversal on the matrix
Start top row left to right: 1,2,3
Right column top to bottom: 6,9
Bottom row right to left: 8,7
Left column bottom to top: 4
Now inner layer: 5Step 2: Combine all elements in order
Result array: [1,2,3,6,9,8,7,4,5]Final Answer:
[1, 2, 3, 6, 9, 8, 7, 4, 5] -> Option BQuick Check:
Spiral order matches [1, 2, 3, 6, 9, 8, 7, 4, 5] [OK]
- Reading rows only left to right
- Skipping inner elements
- Mixing traversal directions
while (top < bottom && left < right) {
for (let i = left; i <= right; i++) result.push(matrix[top][i]);
top++;
for (let i = top; i <= bottom; i++) result.push(matrix[i][right]);
right--;
for (let i = right; i >= left; i--) result.push(matrix[bottom][i]);
bottom--;
for (let i = bottom; i >= top; i--) result.push(matrix[i][left]);
left++;
}Solution
Step 1: Analyze the while loop condition
Using < excludes the last row and column when top == bottom or left == right, missing elements.Step 2: Correct the condition
Change while (top < bottom && left < right) to while (top <= bottom && left <= right) to include all layers.Final Answer:
The while loop condition should use <= instead of < to include last row and column -> Option CQuick Check:
Use <= in loop condition to cover all edges [OK]
- Using < excludes last layer elements
- Not updating boundaries inside loop
- Forgetting to check conditions before loops
Ready to prove it?
Pass the test and this pattern moves unknown
