Bird
Raised Fist0
DSA Typescriptprogramming

Spiral Matrix Traversal in DSA Typescript

Choose your learning style10 modes available
Mental Model
We move around the edges of the matrix in a circle, peeling off one layer at a time until all elements are visited.
Analogy: Imagine peeling an onion layer by layer, starting from the outer skin and moving inward in a spiral path.
1  2  3  4
5  6  7  8
9 10 11 12
13 14 15 16
Dry Run Walkthrough
Input: matrix: [[1,2,3],[4,5,6],[7,8,9]]
Goal: Print all elements in spiral order: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Step 1: Traverse top row from left to right
Visited: 1 -> 2 -> 3
Remaining matrix:
[4,5,6]
[7,8,9]
Why: Start from the top edge to collect the first layer
Step 2: Traverse right column from top to bottom (excluding already visited top row)
Visited: 1 -> 2 -> 3 -> 6 -> 9
Remaining matrix:
[4,5]
[7,8]
Why: Move down the right edge to continue the spiral
Step 3: Traverse bottom row from right to left
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7
Remaining matrix:
[4,5]
Why: Collect elements along the bottom edge in reverse
Step 4: Traverse left column from bottom to top (excluding already visited bottom and top rows)
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4
Remaining matrix:
[5]
Why: Move up the left edge to complete the outer layer
Step 5: Traverse the remaining middle element
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Remaining matrix: empty
Why: Collect the last remaining element in the center
Result:
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Annotated Code
DSA Typescript
class SpiralMatrix {
  static spiralOrder(matrix: number[][]): number[] {
    const result: number[] = [];
    if (matrix.length === 0) return 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 to process
for (let col = left; col <= right; col++) { result.push(matrix[top][col]); }
collect top row elements from left to right
top++;
move top boundary down after processing top row
for (let row = top; row <= bottom; row++) { result.push(matrix[row][right]); }
collect right column elements from top to bottom
right--;
move right boundary left after processing right column
if (top <= bottom) { for (let col = right; col >= left; col--) { result.push(matrix[bottom][col]); } bottom--; }
collect bottom row elements from right to left if still valid
if (left <= right) { for (let row = bottom; row >= top; row--) { result.push(matrix[row][left]); } left++; }
collect left column elements from bottom to top if still valid
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 repeated scanning, this approach visits each element once in a controlled spiral order, avoiding repeated visits and extra checks
Edge Cases
empty matrix
returns empty list immediately
DSA Typescript
if (matrix.length === 0) return result;
single row matrix
traverses left to right only
DSA Typescript
while (top <= bottom && left <= right)
single column matrix
traverses top to bottom only
DSA Typescript
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 peel layers one by one.
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 avoid revisiting
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 starting from the outer layer moving inward.
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 in a circular pattern starting from the outer layer moving inward
B. Traverse the matrix row by row from top to bottom
C. Traverse the matrix column by column from left to right
D. Traverse only the diagonal elements of the matrix

Solution

  1. Step 1: Understand traversal pattern

    Spiral traversal means moving around the edges of the matrix first, 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 A
  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 only
  • Ignoring inward movement after outer layer
2. Which of the following TypeScript code snippets correctly initializes variables for spiral traversal boundaries?
easy
A. let top = -1, bottom = matrix.length - 1, left = -1, right = matrix[0].length - 1;
B. let top = 1, bottom = matrix.length, left = 1, right = matrix[0].length;
C. let top = 0, bottom = matrix.length, left = 0, right = matrix[0].length;
D. let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;

Solution

  1. 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.
  2. 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.
  3. Final Answer:

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

    Boundaries start at 0 and end at length-1 [OK]
Hint: Remember array indices start at 0 [OK]
Common Mistakes:
  • Using length instead of length - 1 for boundaries
  • Starting top or left at 1 instead of 0
  • Using negative indices incorrectly
3. Given a rectangular matrix with 3 rows and 5 columns, how many elements will be printed after a complete spiral traversal?
easy
A. 15
B. 8
C. 12
D. 10

Solution

  1. Step 1: Calculate total elements in matrix

    Number of elements = rows x columns = 3 x 5 = 15.
  2. Step 2: Understand spiral traversal covers all elements

    Spiral traversal visits every element exactly once, so all 15 elements are printed.
  3. Final Answer:

    15 -> Option A
  4. Quick Check:

    Total elements = rows x columns = 15 [OK]
Hint: Spiral prints all elements once [OK]
Common Mistakes:
  • Confusing spiral length with perimeter
  • Counting only outer layer elements
  • Ignoring rectangular shape
4. What is the output of the following TypeScript code for spiral traversal?
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));
medium
A. [1, 4, 7, 8, 9, 6, 3, 2, 5]
B. [1, 2, 3, 6, 9, 8, 7, 4, 5]
C. [1, 2, 3, 4, 5, 6, 7, 8, 9]
D. [9, 8, 7, 4, 1, 2, 3, 6, 5]

Solution

  1. 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: 5
  2. Step 2: Combine all elements in order

    Result array: [1,2,3,6,9,8,7,4,5]
  3. Final Answer:

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

    Spiral order matches [1, 2, 3, 6, 9, 8, 7, 4, 5] [OK]
Hint: Visualize peeling matrix edges in order [OK]
Common Mistakes:
  • Reading rows only left to right
  • Skipping inner elements
  • Mixing traversal directions
5. Identify the bug in this spiral traversal code snippet:
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++;
}
medium
A. The for loops should use < instead of <= to avoid index out of bounds
B. The variables top, bottom, left, right are not initialized
C. The while loop condition should use <= instead of < to include last row and column
D. The result array is not declared before the loop

Solution

  1. Step 1: Analyze the while loop condition

    Using < excludes the last row and column when top == bottom or left == right, missing elements.
  2. Step 2: Correct the condition

    Change while (top < bottom && left < right) to while (top <= bottom && left <= right) to include all layers.
  3. Final Answer:

    The while loop condition should use <= instead of < to include last row and column -> Option C
  4. Quick Check:

    Use <= in loop condition to cover all edges [OK]
Hint: Use <= to include boundary rows and columns [OK]
Common Mistakes:
  • Using < excludes last layer elements
  • Not updating boundaries inside loop
  • Forgetting to check conditions before loops
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