Bird
Raised Fist0
DSA Typescriptprogramming~15 mins

Spiral Matrix Traversal in DSA Typescript - Deep Dive

Choose your learning style10 modes available
Overview - Spiral Matrix Traversal
What is it?
Spiral Matrix Traversal is a way to visit all elements of a 2D grid or matrix in a spiral order, starting from the top-left corner and moving inward in a circular path. Imagine walking around the edges of the matrix first, then moving one layer inside and repeating until all elements are visited. This method helps to process matrix data in a unique pattern that is different from row-wise or column-wise traversal.
Why it matters
Without spiral traversal, we would only access matrix elements in simple straight lines, missing patterns or problems that require circular or layered access. Spiral traversal is useful in image processing, game development, and solving puzzles where the order of visiting elements matters. It helps us think about data in layers and can simplify complex problems involving grids.
Where it fits
Before learning spiral traversal, you should understand basic matrix representation and simple row-wise or column-wise traversal. After mastering spiral traversal, you can explore related topics like boundary traversal, zigzag traversal, and matrix rotation algorithms.
Mental Model
Core Idea
Spiral Matrix Traversal is like peeling an onion layer by layer, visiting the outer edges first and then moving inward until all layers are covered.
Think of it like...
Imagine walking around a square garden fence, collecting flowers along the way. After one round, you step inside the garden and walk around the next smaller fence, repeating until you reach the center.
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ 1 -> 2 -> 3 ->│
│ ↓         ↑ │
│ 8         4 │
│ ↓         ↑ │
│ 7 ← 6 ← 5  │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Traversal order: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8
Build-Up - 7 Steps
1
FoundationUnderstanding Matrix Basics
šŸ¤”
Concept: Learn what a matrix is and how to access its elements using row and column indices.
A matrix is a grid of numbers arranged in rows and columns. For example, a 3x3 matrix has 3 rows and 3 columns. You can access an element by specifying its row and column number, like matrix[row][column]. For instance, matrix[0][0] is the top-left element.
Result
You can read or write any element in the matrix by its position.
Understanding how to access matrix elements is essential before trying any special traversal like spiral order.
2
FoundationSimple Row-wise and Column-wise Traversal
šŸ¤”
Concept: Learn how to visit all elements of a matrix row by row or column by column.
Row-wise traversal means visiting elements from left to right in each row, moving from the top row to the bottom. Column-wise traversal means visiting elements from top to bottom in each column, moving from the left column to the right. For example, in row-wise traversal of a 3x3 matrix, you visit elements in this order: matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], and so on.
Result
You can print or process all elements in a simple linear order.
Knowing these basic traversals helps you appreciate the difference and complexity of spiral traversal.
3
IntermediateDefining Boundaries for Spiral Layers
šŸ¤”Before reading on: do you think we need to track just one boundary or multiple boundaries to traverse in a spiral? Commit to your answer.
Concept: Introduce the idea of four boundaries (top, bottom, left, right) that define the current layer of the matrix to traverse.
To traverse in a spiral, we keep track of four boundaries: top row, bottom row, left column, and right column. Initially, top = 0, bottom = last row index, left = 0, right = last column index. We move along these boundaries in order: left to right (top row), top to bottom (right column), right to left (bottom row), and bottom to top (left column). After completing one layer, we move the boundaries inward to the next layer.
Result
We can isolate each layer of the matrix and know exactly which elements to visit next.
Tracking four boundaries allows controlled movement and prevents revisiting elements or going out of bounds.
4
IntermediateImplementing Spiral Traversal Loop
šŸ¤”Before reading on: do you think the loop should stop when top crosses bottom or left crosses right? Commit to your answer.
Concept: Use a loop that continues while the top boundary is less than or equal to bottom and left boundary is less than or equal to right.
Inside the loop, traverse the top row from left to right, then increment top. Next, traverse the right column from top to bottom, then decrement right. Then, if top <= bottom, traverse the bottom row from right to left, then decrement bottom. Finally, if left <= right, traverse the left column from bottom to top, then increment left. Repeat until boundaries cross.
Result
All elements are visited in spiral order without repetition or skipping.
The loop condition and boundary updates ensure the spiral moves inward correctly and stops at the right time.
5
IntermediateHandling Edge Cases in Spiral Traversal
šŸ¤”Before reading on: do you think a single row or single column matrix needs special handling? Commit to your answer.
Concept: Learn how to handle matrices with only one row or one column to avoid duplicate visits.
When the matrix has only one row or one column left, the traversal steps for bottom row or left column might overlap with already visited elements. To prevent this, check if top <= bottom before traversing the bottom row, and if left <= right before traversing the left column. This avoids duplicates and errors.
Result
The traversal works correctly for all matrix shapes, including 1xN or Nx1.
Boundary checks prevent revisiting elements and ensure correctness for all matrix sizes.
6
AdvancedTypeScript Implementation of Spiral Traversal
šŸ¤”Before reading on: do you think the traversal result should be a new array or modify the original matrix? Commit to your answer.
Concept: Write a complete TypeScript function that returns an array of elements in spiral order without modifying the original matrix.
function 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) { for (let col = left; col <= right; col++) { result.push(matrix[top][col]); } top++; for (let row = top; row <= bottom; row++) { result.push(matrix[row][right]); } right--; if (top <= bottom) { for (let col = right; col >= left; col--) { result.push(matrix[bottom][col]); } bottom--; } if (left <= right) { for (let row = bottom; row >= top; row--) { result.push(matrix[row][left]); } left++; } } return result; } // Example usage: const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; console.log(spiralOrder(matrix));
Result
[1, 2, 3, 6, 9, 8, 7, 4, 5]
Returning a new array preserves the original matrix and makes the function reusable and side-effect free.
7
ExpertOptimizing Spiral Traversal for Large Matrices
šŸ¤”Before reading on: do you think we can reduce the number of boundary checks inside the loop? Commit to your answer.
Concept: Explore ways to minimize checks and improve performance when traversing very large matrices.
In large matrices, frequent boundary checks can add overhead. One optimization is to carefully order traversal steps and update boundaries so that some checks become unnecessary. For example, always check top <= bottom before traversing bottom row and left <= right before left column traversal, but avoid redundant checks inside loops. Also, using simple for loops without extra function calls reduces overhead. Another approach is to flatten the matrix in memory to improve cache performance, but that requires more complex data handling.
Result
Traversal runs faster and uses fewer CPU cycles on large inputs.
Understanding the cost of boundary checks and loop structure helps write more efficient code for performance-critical applications.
Under the Hood
Spiral traversal works by maintaining four pointers that represent the current boundaries of the unvisited matrix area: top row, bottom row, left column, and right column. The algorithm moves along these boundaries in a fixed order, collecting elements and then shrinking the boundaries inward. This process continues until the pointers cross, indicating all elements have been visited. Internally, this prevents revisiting elements and ensures linear time complexity proportional to the number of elements.
Why designed this way?
This design was chosen because it cleanly separates the matrix into layers, making traversal predictable and easy to implement. Alternatives like recursive peeling or marking visited elements add complexity or extra memory usage. The boundary pointer method is memory efficient and intuitive, which is why it became the standard approach.
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ top -> ────────────────-> right │
│ │                         ↑ │
│ │                         │ │
│ left ↑                 ↓ bottom │
│ │                         │ │
│ │                         ↓ │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Traversal order:
1. Move right along top boundary
2. Move down along right boundary
3. Move left along bottom boundary
4. Move up along left boundary

Then shrink boundaries inward and repeat.
Myth Busters - 4 Common Misconceptions
Quick: Do you think spiral traversal always visits elements in a clockwise direction? Commit yes or no.
Common Belief:Spiral traversal always moves clockwise around the matrix.
Tap to reveal reality
Reality:While clockwise spiral traversal is common, spiral traversal can also be done counterclockwise or in other patterns depending on the problem requirements.
Why it matters:Assuming only clockwise traversal limits problem-solving flexibility and can cause confusion when encountering variations.
Quick: Do you think spiral traversal modifies the original matrix? Commit yes or no.
Common Belief:Spiral traversal changes the original matrix by rearranging elements.
Tap to reveal reality
Reality:Spiral traversal only reads elements in a specific order; it does not modify the matrix unless explicitly programmed to do so.
Why it matters:Misunderstanding this can lead to bugs where the original data is unintentionally changed.
Quick: Do you think spiral traversal can be done without tracking boundaries? Commit yes or no.
Common Belief:You can traverse a matrix in spiral order without keeping track of boundaries or visited elements.
Tap to reveal reality
Reality:Tracking boundaries or visited elements is necessary to avoid revisiting or skipping elements during spiral traversal.
Why it matters:Ignoring boundaries leads to infinite loops or incorrect traversal results.
Quick: Do you think spiral traversal always requires extra memory proportional to the matrix size? Commit yes or no.
Common Belief:Spiral traversal always needs extra memory equal to the matrix size to store the result.
Tap to reveal reality
Reality:While storing the traversal result requires extra memory, the traversal itself can be done in-place if the problem allows, by modifying the matrix or using pointers.
Why it matters:Knowing this helps optimize memory usage in constrained environments.
Expert Zone
1
The order of boundary updates is critical; changing it can cause off-by-one errors or missed elements.
2
In non-rectangular or jagged matrices, spiral traversal requires additional checks or adaptations.
3
Cache locality can be poor in spiral traversal compared to row-wise traversal, affecting performance on large data.
When NOT to use
Avoid spiral traversal when you only need simple row-wise or column-wise access, or when random access is more efficient. For very large sparse matrices, specialized traversal methods like coordinate list iteration are better.
Production Patterns
Spiral traversal is used in image processing to apply filters layer by layer, in games for map exploration algorithms, and in UI design for arranging elements in circular patterns. It also appears in coding interviews to test boundary management skills.
Connections
Boundary Traversal of Matrix
Builds-on
Understanding spiral traversal helps grasp boundary traversal, which visits only the outer edges of a matrix without moving inward.
Layered Cake Cutting (Real-world Process)
Similar pattern
Both involve peeling or processing layers one at a time, showing how algorithms can mirror physical processes.
Graph Traversal Algorithms
Conceptual similarity
Spiral traversal can be seen as a special case of graph traversal on a grid graph, helping understand traversal order and boundary conditions.
Common Pitfalls
#1Forgetting to update boundaries after each traversal step.
Wrong approach:while (top <= bottom && left <= right) { for (let col = left; col <= right; col++) { result.push(matrix[top][col]); } // Missing top++ here for (let row = top; row <= bottom; row++) { result.push(matrix[row][right]); } // Missing right-- here // ... rest of traversal }
Correct approach:while (top <= bottom && left <= right) { for (let col = left; col <= right; col++) { result.push(matrix[top][col]); } top++; for (let row = top; row <= bottom; row++) { result.push(matrix[row][right]); } right--; // ... rest of traversal }
Root cause:Not realizing that boundaries must shrink to move inward and avoid revisiting elements.
#2Not checking if top <= bottom before traversing bottom row, causing duplicates.
Wrong approach:for (let col = right; col >= left; col--) { result.push(matrix[bottom][col]); } bottom--;
Correct approach:if (top <= bottom) { for (let col = right; col >= left; col--) { result.push(matrix[bottom][col]); } bottom--; }
Root cause:Ignoring that after updating top, bottom might be less than top, so traversing bottom row would revisit elements.
#3Using incorrect loop conditions causing out-of-bound errors.
Wrong approach:for (let col = left; col < right; col++) { result.push(matrix[top][col]); }
Correct approach:for (let col = left; col <= right; col++) { result.push(matrix[top][col]); }
Root cause:Confusing < and <= in loop conditions leads to missing last elements or accessing invalid indices.
Key Takeaways
Spiral Matrix Traversal visits matrix elements layer by layer, moving inward in a circular path.
Tracking four boundaries (top, bottom, left, right) is essential to control traversal and avoid revisiting elements.
Boundary checks prevent errors and handle edge cases like single rows or columns.
Implementing spiral traversal in TypeScript involves careful loop and boundary management to produce a new ordered list.
Understanding spiral traversal deepens your grasp of matrix manipulation and prepares you for complex grid-based problems.

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