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
- Create
resultas an empty mutable vector withVec::new(). - Create
topandbottom.topstarts at 0 andbottomatmatrix.len() as i32 - 1. They are signed because the boundaries can cross, andrightcan reach -1. - Create
leftandrightthe same way, with the last column's index taken from the first row:matrix[0].len() as i32 - 1. - Loop while
top <= bottom && left <= right. As long as neither pair has crossed, some elements are unread. - Walk the top row with
coloverleft..=right. - Push
matrix[top as usize][col as usize]for each column. - Move
topdown by one. Doing it right after the top row keeps the top-right corner from being read again by the next side. - Walk the right column with
rowovertop..=bottom. - Push
matrix[row as usize][right as usize]. - Move
rightleft by one. - Check
top <= bottom. If a single row was left, it was just read as the top row, andtophas passedbottom. - Inside it, walk the bottom row backwards, with
colover(left..=right).rev(). - Push
matrix[bottom as usize][col as usize]. - Move
bottomup by one. - Check
left <= right. If a single column was left, it was just read as the right column. - Inside it, walk the left column upwards, with
rowover(top..=bottom).rev(). - Push
matrix[row as usize][left as usize]. - Move
leftright by one, which ends the lap. - Return
resultafter 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,
usizeindexes.len()returns ausize, which can't hold -1, andrightorbottomcan legitimately reach -1 (a one-column matrix ends withright = -1). Casting withas i32letsrightandbottomgo below zero, and each index is cast back withas usizewhere the vector is read. The other boundaries,topandleft, get the typei32from the comparisons with them, so the code needs no annotations. - Inclusive ranges.
left..=rightincludesright. 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 afor. .rev()walks a range backwards, so(left..=right).rev()goes fromrightdown toleft.- Type inference for
result.Vec::new()has no element type until the firstpushof ani32, and the return type confirms it. return result;at the end is legal; the idiomatic form is a bareresultwithout 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
ifchecks 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 thenrightbecomes -1, so theleft <= rightcheck skips the upward walk. - One row.
[[1, 2, 3, 4]]gives[1, 2, 3, 4]. After the top row,topis 1 andbottomis 0, so thetop <= bottomcheck 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
topbefore the right column. The right column would start at rowtopagain 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].
