Start learning free

LESSON 50 OF 314 · MATRIX

Spiral Matrix in Rust: Walking Four Shrinking Boundaries

Practice O(m*n) Read the full explanation

You get a grid matrix of integers, with m rows and n columns.

Return a Vec of its values in spiral order.

matrix is an array of rows. Each row is an array of integers. Row 0 is the top row. Column 0 is the leftmost column.

The spiral starts at the top-left value and goes clockwise around the edge. It goes right along the top row, then down the right column. Then it goes left along the bottom row and up the left column.

Next, it does the same with the smaller grid inside, and so on. It takes each value exactly once.

 

Example 1:

Input: matrix = [
  [5, 1, 8],
  [0, 3, 2],
  [9, 7, 4]
]
Output: [5, 1, 8, 2, 4, 7, 9, 0, 3]
Explanation: The spiral first goes around the edge:
5, 1 and 8 across the top,
2 and 4 down the right side,
7 and 9 back along the bottom,
0 up the left side.
3 is left in the middle.

Example 2:

Input: matrix = [
  [3, -1, 7],
  [6, 0, 2],
  [1, 5, 9],
  [8, 8, 4]
]
Output: [3, -1, 7, 2, 9, 4, 8, 8, 1, 6, 0, 5]
Explanation: The spiral first goes around the edge:
3, -1 and 7 across the top,
2, 9 and 4 down the right side,
8 and 8 back along the bottom,
1 and 6 up the left side.
Inside, one column is left.
It gives 0, then the 5 below it.

Example 3:

Input: matrix = [
  [-4, 0, 4]
]
Output: [-4, 0, 4]
Explanation: There is only one row.
The spiral goes right along it and stops.
No value is taken twice.

 

Constraints:

  • m and n are each from 1 to 500.
  • Each value is an integer from -1000 to 1000.
  • Negative values and repeats are allowed.

Note:

Your algorithm should run in O(m * n) time: it visits every element once.

STEP 1 OF 19
    Ctrl + Enter to check

    RUST · MATRIX

    Spiral Matrix in Rust, explained

    Problem overview

    The function spiral_order receives matrix, a vector of rows with m rows and n columns, and returns a vector holding every element in spiral order. The spiral starts at the top-left corner and goes clockwise around the outside: the top row from left to right, the right column from top to bottom, the bottom row from right to left and the left column from bottom to top. Then it repeats on what is left inside, until every element has been visited once.

    For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the answer is [1, 2, 3, 6, 9, 8, 7, 4, 5]: one lap around the outside, then the lone 5 in the middle. The matrix doesn't have to be square. For a 3 by 4 matrix, the outside gives 1, 2, 3, 4, 8, 12, 11, 10, 9, 5 and a single row, 6, 7, is left inside. The time budget is O(m * n), since every element is visited once.

    Approach: four boundaries that move inward

    Instead of tracking a direction and a visited grid, keep four numbers for the part of the matrix that hasn't been read yet: top and bottom are its first and last rows, left and right its first and last columns. One lap of the loop reads the four sides of that rectangle in order, and each finished side moves its boundary one step inward: top down, right left, bottom up, left right.

    On the 3 by 3 example, the first lap runs with top = 0, bottom = 2, left = 0, right = 2. After it, every boundary has moved one step in, and the second lap runs with all four equal to 1, a single cell. That lap reads 5, and the boundaries then cross, which ends the loop.

    The delicate part is the end of a lap. When only one row or one column is left, walking all four sides would read some elements twice. The two if checks before the bottom and left sides prevent that.

    Step by step

    1. Create result as an empty mutable vector with Vec::new().
    2. Create top and bottom. top starts at 0 and bottom at matrix.len() as i32 - 1. They are signed because the boundaries can cross, and right can reach -1.
    3. Create left and right the same way, with the last column's index taken from the first row: matrix[0].len() as i32 - 1.
    4. Loop while top <= bottom && left <= right. As long as neither pair has crossed, some elements are unread.
    5. Walk the top row with col over left..=right.
    6. Push matrix[top as usize][col as usize] for each column.
    7. Move top down by one. Doing it right after the top row keeps the top-right corner from being read again by the next side.
    8. Walk the right column with row over top..=bottom.
    9. Push matrix[row as usize][right as usize].
    10. Move right left by one.
    11. Check top <= bottom. If a single row was left, it was just read as the top row, and top has passed bottom.
    12. Inside it, walk the bottom row backwards, with col over (left..=right).rev().
    13. Push matrix[bottom as usize][col as usize].
    14. Move bottom up by one.
    15. Check left <= right. If a single column was left, it was just read as the right column.
    16. Inside it, walk the left column upwards, with row over (top..=bottom).rev().
    17. Push matrix[row as usize][left as usize].
    18. Move left right by one, which ends the lap.
    19. Return result after the loop.

    The solution in Rust

    impl Solution {
        fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
            let mut result = Vec::new();
            let mut top = 0;
            let mut bottom = matrix.len() as i32 - 1;
            let mut left = 0;
            let mut right = matrix[0].len() as i32 - 1;
            while top <= bottom && left <= right {
                for col in left..=right {
                    result.push(matrix[top as usize][col as usize]);
                }
                top += 1;
                for row in top..=bottom {
                    result.push(matrix[row as usize][right as usize]);
                }
                right -= 1;
                if top <= bottom {
                    for col in (left..=right).rev() {
                        result.push(matrix[bottom as usize][col as usize]);
                    }
                    bottom -= 1;
                }
                if left <= right {
                    for row in (top..=bottom).rev() {
                        result.push(matrix[row as usize][left as usize]);
                    }
                    left += 1;
                }
            }
            return result;
        }
    }
    

    The Rust details worth a closer look:

    • Signed boundaries, usize indexes. len() returns a usize, which can't hold -1, and right or bottom can legitimately reach -1 (a one-column matrix ends with right = -1). Casting with as i32 lets right and bottom go below zero, and each index is cast back with as usize where the vector is read. The other boundaries, top and left, get the type i32 from the comparisons with them, so the code needs no annotations.
    • Inclusive ranges. left..=right includes right. When the start is past the end, the range is empty and the loop body never runs. That is what makes a crossed boundary harmless inside a for.
    • .rev() walks a range backwards, so (left..=right).rev() goes from right down to left.
    • Type inference for result. Vec::new() has no element type until the first push of an i32, and the return type confirms it.
    • return result; at the end is legal; the idiomatic form is a bare result without a semicolon, and both give the same value.
    • Indexing panics. An out-of-range index stops the program with a panic. The loop conditions and the two if checks guarantee every index is inside the matrix.

    Complexity

    Time: O(m * n). Each element is pushed exactly once, and each push costs constant time on average. The boundary checks add only a constant amount per lap, and there are at most about half of min(m, n) laps.

    Space: O(1) beyond the output. The four boundaries are the only extra state. The result vector holds m * n numbers, which the problem requires.

    Edge cases and common mistakes

    • One column. [[3], [2], [1]] gives [3, 2, 1]. The top row reads 3, the right column reads 2 and 1, and then right becomes -1, so the left <= right check skips the upward walk.
    • One row. [[1, 2, 3, 4]] gives [1, 2, 3, 4]. After the top row, top is 1 and bottom is 0, so the top <= bottom check skips the walk back along the bottom.
    • Dropping the two checks. Without them, the one-column example returns [3, 2, 1, 2] and the one-row example returns [1, 2, 3, 4, 3, 2, 1], with elements visited a second time.
    • A single element. [[7]] gives [7].
    • A 2 by 2 matrix. [[1, 2], [3, 4]] gives [1, 2, 4, 3]: one lap covers everything, and the loop ends.
    • Forgetting to move top before the right column. The right column would start at row top again and read the top-right corner a second time.
    • Empty input. matrix[0] panics on an empty vector. The constraints guarantee at least one row and one column.

    Testing

    • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] gives [1, 2, 3, 6, 9, 8, 7, 4, 5].
    • [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] gives [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7].
    • [[3], [2], [1]] gives [3, 2, 1].
    • [[1, 2, 3, 4]] gives [1, 2, 3, 4].
    • [[1, 2], [3, 4]] gives [1, 2, 4, 3].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free