Spiral Matrix Traversal in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to traverse a matrix in a spiral way 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 spiralTraversal(matrix) {
const result = [];
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 collects elements of a 2D matrix in a spiral order starting from the top-left corner.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing each element of the matrix exactly once.
- How many times: Each element is visited once through nested loops inside the while loop.
As the matrix size grows, the number of elements to visit grows too.
| 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 with the total number of elements, which is n squared.
Time Complexity: O(n * m)
This means the time grows proportionally to the total number of elements in the matrix.
[X] Wrong: "The spiral traversal takes more time than just visiting all elements once because of the loops inside loops."
[OK] Correct: Even though there are nested loops, each element is visited only once, so the total steps equal the number of elements.
Understanding this helps you explain how to handle matrix traversal efficiently, a common task in coding challenges and real projects.
"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 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 BQuick Check:
Spiral traversal = circular inward movement [OK]
- Confusing spiral with row-wise traversal
- Thinking spiral means diagonal traversal
- Ignoring the inward movement after outer layer
Solution
Step 1: Understand matrix indexing
Matrix indices start at 0, so top and left start at 0, bottom and right at length - 1.Step 2: Check options
let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1; correctly sets boundaries using zero-based indexing. Others use incorrect start or end values.Final Answer:
let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1; -> Option CQuick Check:
Zero-based indexing for boundaries [OK]
- Starting indices at 1 instead of 0
- Using length instead of length - 1 for boundaries
- Setting negative indices incorrectly
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
function spiralTraversal(mat) {
const result = [];
let top = 0, bottom = mat.length - 1;
let left = 0, right = mat[0].length - 1;
while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++) result.push(mat[top][i]);
top++;
for (let i = top; i <= bottom; i++) result.push(mat[i][right]);
right--;
if (top <= bottom) {
for (let i = right; i >= left; i--) result.push(mat[bottom][i]);
bottom--;
}
if (left <= right) {
for (let i = bottom; i >= top; i--) result.push(mat[i][left]);
left++;
}
}
return result;
}
console.log(spiralTraversal(matrix));Solution
Step 1: Traverse top row left to right
Elements: 1, 2, 3Step 2: Traverse right column top to bottom
Elements: 6, 9Step 3: Traverse bottom row right to left
Elements: 8, 7Step 4: Traverse left column bottom to top
Elements: 4Step 5: Traverse inner matrix
Element: 5Final Answer:
[1, 2, 3, 6, 9, 8, 7, 4, 5] -> Option DQuick Check:
Spiral order matches [1,2,3,6,9,8,7,4,5] [OK]
- Mixing order of bottom row traversal
- Skipping the inner element 5
- Incorrect boundary updates causing repeats
function spiral(mat) {
let top = 0, bottom = mat.length - 1;
let left = 0, right = mat[0].length - 1;
const res = [];
while (top < bottom && left < right) {
for (let i = left; i <= right; i++) res.push(mat[top][i]);
top++;
for (let i = top; i <= bottom; i++) res.push(mat[i][right]);
right--;
for (let i = right; i >= left; i--) res.push(mat[bottom][i]);
bottom--;
for (let i = bottom; i >= top; i--) res.push(mat[i][left]);
left++;
}
return res;
}Solution
Step 1: Analyze loop condition
The condition 'top < bottom && left < right' skips the case when top equals bottom or left equals right, missing last row or column.Step 2: Correct condition
Changing to 'top <= bottom && left <= right' ensures all rows and columns are included in traversal.Final Answer:
The while loop condition should be <= instead of < to include single rows or columns -> Option AQuick Check:
Use <= to cover all layers [OK]
- Using < causes missing last row or column
- Changing for loop bounds incorrectly
- Swapping top and bottom variables
const 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
Elements: 1, 2, 3, 4Step 2: Traverse right column top to bottom
Elements: 8, 12Step 3: Traverse bottom row right to left
Elements: 11, 10, 9Step 4: Traverse left column bottom to top
Element: 5Step 5: Traverse inner row left to right
Elements: 6, 7Final Answer:
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] -> Option AQuick Check:
Follow edges clockwise, then inner row [OK]
- Mixing order of inner elements
- Skipping last inner row
- Confusing left column traversal order
Ready to prove it?
Pass the test and this pattern moves unknown
