Bird
Raised Fist0
DSA Rustprogramming~20 mins

Spiral Matrix Traversal in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Spiral Matrix Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Spiral Traversal on 3x3 Matrix
What is the output of the spiral traversal on the following 3x3 matrix?

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
DSA Rust
fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
    let mut result = Vec::new();
    if matrix.is_empty() { return result; }
    let (mut top, mut bottom) = (0, matrix.len() - 1);
    let (mut left, mut right) = (0, matrix[0].len() - 1);
    while left <= right && top <= bottom {
        for i in left..=right {
            result.push(matrix[top][i]);
        }
        top += 1;
        for i in top..=bottom {
            result.push(matrix[i][right]);
        }
        right -= 1;
        if top <= bottom {
            for i in (left..=right).rev() {
                result.push(matrix[bottom][i]);
            }
            bottom -= 1;
        }
        if left <= right {
            for i in (top..=bottom).rev() {
                result.push(matrix[i][left]);
            }
            left += 1;
        }
    }
    result
}

fn main() {
    let matrix = vec![
        vec![1, 2, 3],
        vec![4, 5, 6],
        vec![7, 8, 9],
    ];
    let output = spiral_order(matrix);
    println!("{:?}", output);
}
A[1, 2, 3, 6, 9, 8, 7, 4, 5]
B[1, 4, 7, 8, 9, 6, 3, 2, 5]
C[1, 2, 3, 4, 5, 6, 7, 8, 9]
D[1, 3, 5, 7, 9, 2, 4, 6, 8]
Attempts:
2 left
💡 Hint
Traverse the matrix edges in clockwise order, shrinking the boundaries after each edge.
❓ Predict Output
intermediate
2:00remaining
Spiral Traversal Output for 2x4 Matrix
What is the output of the spiral traversal on this 2x4 matrix?

[[1, 2, 3, 4], [5, 6, 7, 8]]
DSA Rust
fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
    let mut result = Vec::new();
    if matrix.is_empty() { return result; }
    let (mut top, mut bottom) = (0, matrix.len() - 1);
    let (mut left, mut right) = (0, matrix[0].len() - 1);
    while left <= right && top <= bottom {
        for i in left..=right {
            result.push(matrix[top][i]);
        }
        top += 1;
        for i in top..=bottom {
            result.push(matrix[i][right]);
        }
        right -= 1;
        if top <= bottom {
            for i in (left..=right).rev() {
                result.push(matrix[bottom][i]);
            }
            bottom -= 1;
        }
        if left <= right {
            for i in (top..=bottom).rev() {
                result.push(matrix[i][left]);
            }
            left += 1;
        }
    }
    result
}

fn main() {
    let matrix = vec![
        vec![1, 2, 3, 4],
        vec![5, 6, 7, 8],
    ];
    let output = spiral_order(matrix);
    println!("{:?}", output);
}
A[1, 4, 8, 7, 6, 5, 2, 3]
B[1, 5, 6, 7, 8, 4, 3, 2]
C[1, 2, 3, 4, 8, 7, 6, 5]
D[1, 2, 3, 4, 5, 6, 7, 8]
Attempts:
2 left
💡 Hint
Remember to traverse the top row, then right column, then bottom row in reverse, then left column in reverse.
🔧 Debug
advanced
2:00remaining
Identify the Error in Spiral Traversal Code
What error will this Rust code produce when run on a non-empty matrix?
DSA Rust
fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
    let mut result = Vec::new();
    let (mut top, mut bottom) = (0, matrix.len());
    let (mut left, mut right) = (0, matrix[0].len());
    while left <= right && top <= bottom {
        for i in left..=right {
            result.push(matrix[top][i]);
        }
        top += 1;
        for i in top..=bottom {
            result.push(matrix[i][right]);
        }
        if top <= bottom {
            for i in (left..=right).rev() {
                result.push(matrix[bottom][i]);
            }
            bottom -= 1;
        }
        if left <= right {
            for i in (top..=bottom).rev() {
                result.push(matrix[i][left]);
            }
            left += 1;
        }
    }
    result
}
AIndex out of bounds panic at runtime
BInfinite loop causing program to hang
CCompilation error: cannot borrow immutable as mutable
DNo error, runs correctly
Attempts:
2 left
💡 Hint
Check how bottom and right are initialized compared to matrix length.
❓ Predict Output
advanced
2:00remaining
Spiral Traversal Output for 4x4 Matrix
What is the output of the spiral traversal on this 4x4 matrix?

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
DSA Rust
fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
    let mut result = Vec::new();
    if matrix.is_empty() { return result; }
    let (mut top, mut bottom) = (0, matrix.len() - 1);
    let (mut left, mut right) = (0, matrix[0].len() - 1);
    while left <= right && top <= bottom {
        for i in left..=right {
            result.push(matrix[top][i]);
        }
        top += 1;
        for i in top..=bottom {
            result.push(matrix[i][right]);
        }
        right -= 1;
        if top <= bottom {
            for i in (left..=right).rev() {
                result.push(matrix[bottom][i]);
            }
            bottom -= 1;
        }
        if left <= right {
            for i in (top..=bottom).rev() {
                result.push(matrix[i][left]);
            }
            left += 1;
        }
    }
    result
}

fn main() {
    let matrix = vec![
        vec![1, 2, 3, 4],
        vec![5, 6, 7, 8],
        vec![9, 10, 11, 12],
        vec![13, 14, 15, 16],
    ];
    let output = spiral_order(matrix);
    println!("{:?}", output);
}
A[1, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10, 2, 3]
B[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
C[1, 5, 9, 13, 14, 15, 16, 12, 8, 4, 3, 2, 6, 10, 11, 7]
D[1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
Attempts:
2 left
💡 Hint
Follow the spiral edges carefully, shrinking boundaries after each pass.
🧠 Conceptual
expert
2:00remaining
Time Complexity of Spiral Matrix Traversal
What is the time complexity of the spiral matrix traversal algorithm for an m x n matrix?
AO(1) because it uses constant extra space
BO(m * n) because each element is visited exactly once
CO(m * n * min(m, n)) because of nested loops inside the traversal
DO(m + n) because it traverses only the edges of the matrix
Attempts:
2 left
💡 Hint
Consider how many times each element is accessed during traversal.

Practice

(1/5)
1. What is the main idea behind Spiral Matrix Traversal?
easy
A. Traverse the matrix column by column from left to right
B. Traverse the matrix row by row from top to bottom
C. Traverse the matrix in a circular pattern from outer to inner layers
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 and gradually moving inward in a circular way.
  2. Step 2: Compare options

    Only Traverse the matrix in a circular pattern from outer to inner layers describes this circular, layer-by-layer movement. Others describe linear or partial traversals.
  3. Final Answer:

    Traverse the matrix in a circular pattern from outer to inner layers -> Option C
  4. Quick Check:

    Spiral traversal = circular outer to inner [OK]
Hint: Think of peeling an onion layer by layer [OK]
Common Mistakes:
  • Confusing spiral with row-wise or column-wise traversal
  • Thinking only diagonals are involved
  • Ignoring the inward movement after outer layer
2. Which Rust loop structure is best suited to iterate over matrix indices for spiral traversal?
easy
A. loop { ... } with break condition
B. for i in 0..n { ... }
C. while i <= n { ... }
D. match statement for index matching

Solution

  1. Step 1: Identify loop types in Rust

    Rust commonly uses for i in 0..n for fixed range iteration, ideal for matrix indices.
  2. Step 2: Evaluate options for spiral traversal

    for i in 0..n { ... } uses range-based for loop, perfect for controlled index traversal. while i <= n { ... } is less idiomatic. loop { ... } with break condition is infinite loop needing manual breaks. match statement for index matching is for pattern matching, not iteration.
  3. Final Answer:

    for i in 0..n { ... } -> Option B
  4. Quick Check:

    Range-based for loop = best for index iteration [OK]
Hint: Use for loops with ranges for matrix indices [OK]
Common Mistakes:
  • Using infinite loops without proper break
  • Using while loops without clear index control
  • Misusing match for iteration
3. What is the output of the spiral traversal on this 3x3 matrix?
let matrix = vec![
  vec![1, 2, 3],
  vec![4, 5, 6],
  vec![7, 8, 9],
];
// Spiral traversal code prints elements in order
medium
A. [1, 2, 3, 6, 9, 8, 7, 4, 5]
B. [1, 4, 7, 8, 9, 6, 3, 2, 5]
C. [1, 2, 3, 4, 5, 6, 7, 8, 9]
D. [9, 8, 7, 6, 5, 4, 3, 2, 1]

Solution

  1. Step 1: Trace spiral traversal order

    Start top row left to right: 1, 2, 3; then right column down: 6, 9; bottom row right to left: 8, 7; left column up: 4; center element: 5.
  2. Step 2: Write elements in order

    Combined order is [1, 2, 3, 6, 9, 8, 7, 4, 5].
  3. Final Answer:

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

    Outer to inner spiral = [1,2,3,6,9,8,7,4,5] [OK]
Hint: Follow edges clockwise, then move inward [OK]
Common Mistakes:
  • Listing elements row-wise instead of spiral
  • Reversing order of bottom or left edges
  • Skipping center element
4. Identify the bug in this Rust spiral traversal snippet:
let mut top = 0;
let mut bottom = matrix.len() - 1;
let mut left = 0;
let mut right = matrix[0].len() - 1;
while top <= bottom && left <= right {
  for i in left..=right {
    print!("{} ", matrix[top][i]);
  }
  top += 1;
  for i in top..=bottom {
    print!("{} ", matrix[i][right]);
  }
  right -= 1;
  for i in (left..=right).rev() {
    print!("{} ", matrix[bottom][i]);
  }
  bottom -= 1;
  for i in (top..=bottom).rev() {
    print!("{} ", matrix[i][left]);
  }
  left += 1;
}
medium
A. The loop may print elements twice when top > bottom or left > right
B. The ranges in for loops are incorrect and cause syntax errors
C. The variables top, bottom, left, right are not initialized properly
D. The print statements use wrong matrix indices causing runtime panic

Solution

  1. Step 1: Analyze loop conditions and updates

    The while loop condition is correct, but inside the loop, after updating top, bottom, left, right, the for loops still run without checking if top <= bottom or left <= right again.
  2. Step 2: Identify consequence of missing checks

    This can cause the inner loops to run when top > bottom or left > right, printing elements twice or causing invalid access.
  3. Final Answer:

    The loop may print elements twice when top > bottom or left > right -> Option A
  4. Quick Check:

    Missing inner boundary checks = duplicate prints [OK]
Hint: Check boundaries before each edge traversal [OK]
Common Mistakes:
  • Not checking boundaries inside the loop after updates
  • Assuming while condition covers all cases
  • Ignoring reverse ranges correctness
5. Given a rectangular matrix with dimensions 3x5, how many elements will be printed in spiral traversal, and what is the order of traversal directions?
hard
A. 15 elements; order: left to right, bottom to top, right to left, top to bottom, repeat
B. 15 elements; order: top to bottom, left to right, bottom to top, right to left, repeat
C. 8 elements; order: left to right, top to bottom, right to left, bottom to top, repeat
D. 15 elements; order: left to right, top to bottom, right to left, bottom to top, repeat

Solution

  1. Step 1: Calculate total elements in 3x5 matrix

    3 rows * 5 columns = 15 elements to print in spiral traversal.
  2. Step 2: Identify traversal direction order

    Spiral traversal moves: left to right (top row), top to bottom (right column), right to left (bottom row), bottom to top (left column), then repeats inward.
  3. Final Answer:

    15 elements; order: left to right, top to bottom, right to left, bottom to top, repeat -> Option D
  4. Quick Check:

    3*5=15; spiral directions = LR, TB, RL, BT [OK]
Hint: Count total elements; remember spiral direction cycle [OK]
Common Mistakes:
  • Miscounting total elements
  • Mixing up traversal direction order
  • Assuming fewer elements printed
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