Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

Spiral Matrix Traversal in DSA Javascript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Spiral Matrix Traversal
Start with boundaries: top, bottom, left, right
↓
Traverse from left to right on top row
↓
Move top boundary down
↓
Traverse from top to bottom on right column
↓
Move right boundary left
↓
Traverse from right to left on bottom row
↓
Move bottom boundary up
↓
Traverse from bottom to top on left column
↓
Move left boundary right
↓
Repeat until boundaries cross
We move around the matrix edges in a spiral by adjusting boundaries after each side traversal until all elements are visited.
Execution Sample
DSA Javascript
const spiralOrder = matrix => {
  let result = [];
  let top = 0, bottom = matrix.length - 1;
  let left = 0, right = matrix[0].length - 1;
  while (left <= right && top <= bottom) {
    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 matrix elements in spiral order by moving boundaries inward after each side traversal.
Execution Table
StepOperationBoundaries (top,bottom,left,right)Elements AddedVisual State
1Traverse top row left->right(0,2,0,2)[1,2,3][[1,2,3],[4,5,6],[7,8,9]]
2Move top boundary down(1,2,0,2)[][[1,2,3],[4,5,6],[7,8,9]]
3Traverse right column top->bottom(1,2,0,2)[6,9][[1,2,3],[4,5,6],[7,8,9]]
4Move right boundary left(1,2,0,1)[][[1,2,3],[4,5,6],[7,8,9]]
5Traverse bottom row right->left(1,2,0,1)[8,7][[1,2,3],[4,5,6],[7,8,9]]
6Move bottom boundary up(1,1,0,1)[][[1,2,3],[4,5,6],[7,8,9]]
7Traverse left column bottom->top(1,1,0,1)[4][[1,2,3],[4,5,6],[7,8,9]]
8Move left boundary right(1,1,1,1)[][[1,2,3],[4,5,6],[7,8,9]]
9Traverse top row left->right(1,1,1,1)[5][[1,2,3],[4,5,6],[7,8,9]]
ExitBoundaries crossed (top=2 > bottom=1)(2,1,1,0)Traversal complete[[1,2,3],[4,5,6],[7,8,9]]
💡 top boundary (2) crossed bottom boundary (1), traversal ends
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 6After Step 8Final
top011112
bottom222111
left000011
right221110
result[][1,2,3][1,2,3,6,9][1,2,3,6,9,8,7][1,2,3,6,9,8,7,4][1,2,3,6,9,8,7,4,5]
Key Moments - 3 Insights
Why do we check 'if (top <= bottom)' before traversing the bottom row?
Because after moving the top boundary down, top might be greater than bottom, meaning no rows left to traverse. This prevents adding duplicate or invalid elements, as seen in Step 5 of the execution_table.
Why do boundaries cross and stop the loop?
The loop stops when the top boundary goes below bottom or left goes beyond right, meaning all elements are visited. This is shown in the Exit row where top=2 > bottom=1.
How does the spiral traversal avoid revisiting elements?
By moving boundaries inward after each side traversal (top++, bottom--, left++, right--), the traversal area shrinks, preventing revisits. This is tracked in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 3, which elements are added to the result?
A[4,5,6]
B[6,9]
C[8,7]
D[1,2,3]
💡 Hint
Check the 'Elements Added' column at Step 3 in execution_table
At which step does the bottom boundary move up?
AStep 6
BStep 2
CStep 4
DStep 8
💡 Hint
Look at the 'Operation' column for 'Move bottom boundary up' in execution_table
If the matrix had 4 rows instead of 3, how would the variable 'bottom' change after Step 6?
AIt would remain 1
BIt would be 3 instead of 1
CIt would be 2 instead of 1
DIt would be 0
💡 Hint
Check variable_tracker for 'bottom' and consider one less after moving bottom boundary up
Concept Snapshot
Spiral Matrix Traversal:
- Use four boundaries: top, bottom, left, right
- Traverse edges in order: top row, right column, bottom row, left column
- After each edge, move the boundary inward
- Repeat until boundaries cross
- Collect elements in traversal order into result array
Full Transcript
Spiral Matrix Traversal moves around the matrix edges in a spiral pattern. We start with four boundaries: top, bottom, left, and right. We first traverse the top row from left to right, then move the top boundary down. Next, we traverse the right column from top to bottom, then move the right boundary left. Then we traverse the bottom row from right to left, moving the bottom boundary up, and finally traverse the left column from bottom to top, moving the left boundary right. We repeat these steps until the boundaries cross, meaning all elements are visited. This process collects all elements in spiral order without repeats.

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