Problem overview
The method spiralOrder receives a matrix of numbers with m rows and n columns, and returns all its elements in spiral order. The spiral starts at the top-left corner and goes clockwise around the outside: the top row left to right, the right column top to bottom, the bottom row right to left, and the left column bottom to top. Then it repeats on what is left inside, until every element has been visited exactly once. The algorithm must run in O(m * n) time.
For this matrix:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
the answer is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]. The outside gives 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, and what is left inside is a single row, 6 and 7.
Approach: four boundaries that move inward
There is no formula for the position of the k-th element, and tracking a direction with turns and "already visited" marks is fiddly. A simpler idea is to keep four numbers that describe the part of the matrix not visited yet: top and bottom are its first and last rows, left and right its first and last columns.
One lap of a while loop walks the four sides of that part, and each finished side moves its boundary one step inward: after the top row, top goes down by one; after the right column, right goes left by one; and so on. The loop ends when a pair of boundaries crosses, which means nothing is left.
Each element is pushed once, so the time is proportional to the number of elements.
Step by step
- Create
result, an emptynumber[], to collect elements in the order the spiral reaches them. - Set the row boundaries:
topis 0 andbottomismatrix.length - 1. - Set the column boundaries:
leftis 0 andrightismatrix[0].length - 1. Every row has the same length, so the first row tells the number of columns. - Loop while
top <= bottom && left <= right. While neither pair has crossed, some elements remain. - Walk the top row from
lefttoright, both included, pushingmatrix[top][col]. - Move
topdown. Doing it right away keeps the top-right corner from being visited again by the next walk. - Walk the right column from the new
toptobottom, pushingmatrix[row][right]. - Move
rightone column to the left. - Walk the bottom row only if
top <= bottom. When just one row was left, it was walked as the top row, andtophas passedbottom. Walking it back would repeat its elements. The walk goes fromrightdown toleft, thenbottommoves up. - Walk the left column only if
left <= right, for the same reason when one column was left. It goes frombottomup totop, thenleftmoves right. - Return
result.
The solution in TypeScript
class Solution {
spiralOrder(matrix: number[][]): number[] {
let result: number[] = [];
let top = 0, bottom = matrix.length - 1;
let left = 0, 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;
}
}
Some TypeScript details:
- Several variables in one
let.let top = 0, bottom = matrix.length - 1;declares two variables. Both are inferred asnumber. matrix[row][col]is row first. The first index picks the row (an inner array), the second picks the column inside it. Mixing them up reads the transposed matrix.- The annotation
number[]onresulttells the compiler what the array will hold. It checks nothing at run time, since types are erased when the code is compiled to JavaScript. letfor the boundaries. They change on every lap, soconstwould not allowtop++.
Complexity
Time: O(m * n). Every element is pushed exactly once, and the guards make sure no side is walked twice. The loop work is proportional to the number of elements.
Space: O(1) beyond the output. The four boundaries and the loop counters are constant. The returned array holds m * n numbers, which is the answer itself.
Edge cases and common mistakes
- A single row. For
[[1, 2, 3]]the top walk collects all three, thentoppassesbottom, so the bottom walk is skipped. Without the first guard the same row would be added again: the unguarded version returns[1, 2, 3, 2, 1]. - A single column. For
[[3], [2], [1]]the answer is[3, 2, 1]. After the right column,rightis belowleft, and the second guard skips the walk up. The unguarded version returns[3, 2, 1, 2]. - Moving a boundary too late. If
topis not increased before the right-column walk, the top-right corner is added twice. - Using
<instead of<=. The loop and the walks include both ends. A final single cell, such as the 5 in the middle of a 3 by 3 matrix, would be skipped with a strict comparison. - Swapped sizes. The row count is
matrix.lengthand the column count ismatrix[0].length. Swapping them makes the boundaries point outside the matrix on any non-square input.
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, 4, 3].[[1]]gives[1].
