Bird
Raised Fist0
DSA Javascriptprogramming

Spiral Matrix Traversal in DSA Javascript

Choose your learning style10 modes available
Mental Model
We walk around the edges of the matrix in a circle, then move inward layer by layer until all elements are visited.
Analogy: Imagine peeling an onion layer by layer, starting from the outer skin and moving towards the center, collecting all pieces as you go.
1 -> 2 -> 3 -> 4
↓           ↑
12         5
↓           ↑
11 ← 10 ← 9 ← 6
      ↓
      7 -> 8
Dry Run Walkthrough
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Goal: Collect all elements in spiral order: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Step 1: Traverse top row from left to right
Collected: [1, 2, 3]
Remaining matrix edges to traverse
Why: Start from the top row to collect the first outer layer
Step 2: Traverse right column from top to bottom (excluding already visited top row)
Collected: [1, 2, 3, 6, 9]
Remaining matrix edges to traverse
Why: Move down the right edge to continue the spiral
Step 3: Traverse bottom row from right to left (excluding already visited right column)
Collected: [1, 2, 3, 6, 9, 8, 7]
Remaining matrix edges to traverse
Why: Move left along the bottom edge to continue the spiral
Step 4: Traverse left column from bottom to top (excluding already visited bottom and top rows)
Collected: [1, 2, 3, 6, 9, 8, 7, 4]
Remaining matrix edges to traverse
Why: Move up the left edge to complete the outer layer
Step 5: Move inward to the next inner layer and traverse the remaining element
Collected: [1, 2, 3, 6, 9, 8, 7, 4, 5]
No more elements left
Why: After completing outer layer, move inward to collect center element
Result:
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Annotated Code
DSA Javascript
class SpiralMatrix {
  static spiralOrder(matrix) {
    if (matrix.length === 0) return [];
    const result = [];
    let top = 0;
    let bottom = matrix.length - 1;
    let left = 0;
    let right = matrix[0].length - 1;

    while (top <= bottom && left <= right) {
      // Traverse from left to right on the top row
      for (let col = left; col <= right; col++) {
        result.push(matrix[top][col]);
      }
      top++;

      // Traverse from top to bottom on the right column
      for (let row = top; row <= bottom; row++) {
        result.push(matrix[row][right]);
      }
      right--;

      if (top <= bottom) {
        // Traverse from right to left on the bottom row
        for (let col = right; col >= left; col--) {
          result.push(matrix[bottom][col]);
        }
        bottom--;
      }

      if (left <= right) {
        // Traverse from bottom to top on the left column
        for (let row = bottom; row >= top; row--) {
          result.push(matrix[row][left]);
        }
        left++;
      }
    }
    return result;
  }
}

// Driver code
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
const spiral = SpiralMatrix.spiralOrder(matrix);
console.log(spiral.join(' -> '));
while (top <= bottom && left <= right) {
continue looping while there are layers left to traverse
for (let col = left; col <= right; col++) { result.push(matrix[top][col]); } top++;
traverse the top row left to right, then move top boundary down
for (let row = top; row <= bottom; row++) { result.push(matrix[row][right]); } right--;
traverse the right column top to bottom, then move right boundary left
if (top <= bottom) { for (let col = right; col >= left; col--) { result.push(matrix[bottom][col]); } bottom--; }
traverse the bottom row right to left if still valid, then move bottom boundary up
if (left <= right) { for (let row = bottom; row >= top; row--) { result.push(matrix[row][left]); } left++; }
traverse the left column bottom to top if still valid, then move left boundary right
OutputSuccess
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Complexity Analysis
Time: O(m*n) because every element in the m by n matrix is visited exactly once
Space: O(m*n) for the output list that stores all elements
vs Alternative: Compared to naive approaches that might revisit elements or use extra visited flags, this method is efficient and clean with no repeated visits
Edge Cases
empty matrix
returns an empty list immediately
DSA Javascript
if (matrix.length === 0) return [];
single row matrix
traverses left to right only
DSA Javascript
while (top <= bottom && left <= right) { ... }
single column matrix
traverses top to bottom only
DSA Javascript
while (top <= bottom && left <= right) { ... }
When to Use This Pattern
When you need to visit all elements of a matrix in a circular, inward pattern, use spiral traversal to systematically peel layers.
Common Mistakes
Mistake: Not updating boundaries correctly causing infinite loops or repeated elements
Fix: After each edge traversal, update the corresponding boundary (top, bottom, left, right) to move inward
Mistake: Not checking boundary conditions before traversing bottom row or left column
Fix: Add checks like if (top <= bottom) and if (left <= right) before those traversals
Summary
It collects matrix elements in a spiral order from outer layer to inner layers.
Use it when you want to read or print matrix elements in a circular inward pattern.
The key is to keep track of four boundaries and move them inward after each edge traversal.

Practice

(1/5)
1. What is the main idea behind Spiral Matrix Traversal?
easy
A. Traverse the matrix row by row from top to bottom
B. Traverse the matrix in a circular pattern starting from the outer layer moving inward
C. Traverse the matrix column by column from left to right
D. Traverse the matrix diagonally from top-left to bottom-right

Solution

  1. Step 1: Understand traversal pattern

    Spiral traversal means moving around the edges of the matrix and then moving inward layer by layer.
  2. 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.
  3. Final Answer:

    Traverse the matrix in a circular pattern starting from the outer layer moving inward -> Option B
  4. Quick Check:

    Spiral traversal = circular inward movement [OK]
Hint: Think of peeling an onion layer by layer [OK]
Common Mistakes:
  • Confusing spiral with row-wise traversal
  • Thinking spiral means diagonal traversal
  • Ignoring the inward movement after outer layer
2. Which of the following is the correct way to initialize variables for spiral traversal boundaries in JavaScript?
easy
A. let top = 1, bottom = matrix.length, left = 1, right = matrix[0].length;
B. let top = 0, bottom = matrix.length, left = 0, right = matrix[0].length;
C. let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
D. let top = -1, bottom = matrix.length - 1, left = -1, right = matrix[0].length - 1;

Solution

  1. Step 1: Understand matrix indexing

    Matrix indices start at 0, so top and left start at 0, bottom and right at length - 1.
  2. 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.
  3. Final Answer:

    let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1; -> Option C
  4. Quick Check:

    Zero-based indexing for boundaries [OK]
Hint: Remember arrays start at 0 in JavaScript [OK]
Common Mistakes:
  • Starting indices at 1 instead of 0
  • Using length instead of length - 1 for boundaries
  • Setting negative indices incorrectly
3. What is the output of the following code?
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));
medium
A. [1, 2, 3, 6, 9, 7, 8, 4, 5]
B. [1, 2, 3, 6, 9, 8, 7, 5, 4]
C. [1, 2, 3, 5, 6, 9, 8, 7, 4]
D. [1, 2, 3, 6, 9, 8, 7, 4, 5]

Solution

  1. Step 1: Traverse top row left to right

    Elements: 1, 2, 3
  2. Step 2: Traverse right column top to bottom

    Elements: 6, 9
  3. Step 3: Traverse bottom row right to left

    Elements: 8, 7
  4. Step 4: Traverse left column bottom to top

    Elements: 4
  5. Step 5: Traverse inner matrix

    Element: 5
  6. Final Answer:

    [1, 2, 3, 6, 9, 8, 7, 4, 5] -> Option D
  7. Quick Check:

    Spiral order matches [1,2,3,6,9,8,7,4,5] [OK]
Hint: Follow edges clockwise, then move inward [OK]
Common Mistakes:
  • Mixing order of bottom row traversal
  • Skipping the inner element 5
  • Incorrect boundary updates causing repeats
4. Identify the error in this spiral traversal code snippet:
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;
}
medium
A. The while loop condition should be <= instead of < to include single rows or columns
B. The for loops should use < instead of <= to avoid index errors
C. The variables top and bottom are swapped incorrectly
D. The result array is not initialized properly

Solution

  1. 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.
  2. Step 2: Correct condition

    Changing to 'top <= bottom && left <= right' ensures all rows and columns are included in traversal.
  3. Final Answer:

    The while loop condition should be <= instead of < to include single rows or columns -> Option A
  4. Quick Check:

    Use <= to cover all layers [OK]
Hint: Use <= in loop condition to cover all matrix layers [OK]
Common Mistakes:
  • Using < causes missing last row or column
  • Changing for loop bounds incorrectly
  • Swapping top and bottom variables
5. Given a rectangular matrix of size 3x4:
const matrix = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12]
];

What is the spiral traversal output?
hard
A. [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
B. [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 7, 6]
C. [1, 2, 3, 4, 8, 12, 11, 10, 9, 6, 5, 7]
D. [1, 2, 3, 4, 8, 12, 11, 10, 9, 7, 6, 5]

Solution

  1. Step 1: Traverse top row left to right

    Elements: 1, 2, 3, 4
  2. Step 2: Traverse right column top to bottom

    Elements: 8, 12
  3. Step 3: Traverse bottom row right to left

    Elements: 11, 10, 9
  4. Step 4: Traverse left column bottom to top

    Element: 5
  5. Step 5: Traverse inner row left to right

    Elements: 6, 7
  6. Final Answer:

    [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] -> Option A
  7. Quick Check:

    Follow edges clockwise, then inner row [OK]
Hint: Remember to handle rectangular shapes carefully [OK]
Common Mistakes:
  • Mixing order of inner elements
  • Skipping last inner row
  • Confusing left column traversal order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard