Problem overview
The method spiralOrder(matrix) receives a matrix with m rows and n columns, an array of rows where each row is an array of integers. It returns one array with every element in spiral order. The spiral starts at the top-left corner and goes clockwise around the outside: along the top row, down the right column, back along the bottom row and up the left column. Then it repeats on the part 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]. The outer ring gives 1, 2, 3, 6, 9, 8, 7, 4, and only 5 is left in the middle. The matrix doesn't have to be square: [[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].
Approach: shrink four boundaries
You can't simply loop over rows and columns, because the direction changes at each corner. You could instead mark visited cells and turn right whenever the next cell is outside the matrix or already visited. That works, but it needs an extra grid of marks. A simpler way tracks which part of the matrix is still unvisited with four numbers:
topandbottom: the first and last rows not yet visited;leftandright: the first and last columns not yet visited.
One lap of the loop walks once around that part. After each side is finished, its boundary moves one step inward: top goes down after the top row, right goes left after the right column, and so on. The loop runs while top <= bottom and left <= right, which means some cells are still left. Each element is pushed exactly once, so the running time is O(m * n).
The delicate part is the end of the spiral. When one row or one column is all that remains, the "back along the bottom" or "back up the left" walk would visit the same cells a second time. Two if checks prevent that.
Here are the laps on two of the lesson's examples:
| Matrix | Elements added in the lap | top, bottom, left, right afterwards |
|---|---|---|
| 3 by 3 | 1,2,3,6,9,8,7,4 | 1, 1, 1, 1 |
| 3 by 3 | 5 | 2, 1, 1, 0 |
| 3 by 4 | 1,2,3,4,8,12,11,10,9,5 | 1, 1, 1, 2 |
| 3 by 4 | 6,7 | 2, 1, 2, 1 |
In every case the boundaries cross at the end, so the loop condition stops it.
Step by step
- Start with an empty
resultarray that will collect the elements in visiting order. - Set the row boundaries:
topis 0 andbottomismatrix.length - 1. - Set the column boundaries:
leftis 0 andrightismatrix[0].length - 1. All rows have the same length, so the first row tells the column count. - Loop while both pairs of boundaries are still in order. Each pass walks one ring.
- Walk the top row from
lefttoright, 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], then moverightone column left. - Check that a bottom row is left with
top <= bottom. If only one row remained, it was just walked as the top row, and walking it backwards would repeat its elements. - Walk the bottom row backwards from
rightdown toleft, then movebottomup. - Check that a left column is left with
left <= right, for the same reason: a single remaining column was already walked as the right column. - Walk the left column upwards from
bottomtotop, then moveleftone column right. - Return
resultafter the loop.
The solution in JavaScript
class Solution {
spiralOrder(matrix) {
let result = [];
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 JavaScript details worth knowing:
- Several declarations on one line.
let top = 0, bottom = matrix.length - 1;declares two variables with onelet. Both are reassigned later, soconstwould not work. - Matrices are arrays of arrays.
matrix[top][col]first picks a row, then a cell in it.matrix[0].lengthis the number of columns, andmatrix.lengththe number of rows. - Loops that count down. The bottom and left walks use
col--androw--. Ifrightorbottomhas already crossed its partner, the loop condition is false at once and the loop body never runs. - Reading outside an array doesn't throw. In JavaScript
matrix[5]on a three-row matrix isundefined, butmatrix[5][0]throws aTypeError. The boundary checks keep every access inside the matrix.
Complexity
Time: O(m * n). Every cell is pushed to result exactly once, and the loop condition and checks cost constant time per lap. The number of laps is at most about half of the smaller dimension.
Space: O(1) extra, not counting result, which holds all m * n elements. The function keeps only the four boundaries and the loop counters.
Edge cases and common mistakes
- A single row.
[[1, 2, 3]]must return[1, 2, 3]. Without thetop <= bottomcheck, the bottom walk would add the same row again and give[1, 2, 3, 2, 1]. - A single column.
[[3], [2], [1]]returns[3, 2, 1]. Without theleft <= rightcheck, the left walk would add elements a second time: a version with both checks removed returns[3, 2, 1, 2]. - A leftover row in the middle. For the 3 by 4 example, the second lap holds a single row, 6 and 7. Without the checks the result ends with a stray 6:
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6]. - A single element.
[[5]]gives[5]. - Moving a boundary too late. If
topis not moved right after the top row, the right-column walk starts on the corner again and pushes it twice. - Using the wrong boundary for the walk. The right column runs from
toptobottom, the bottom row fromrighttoleft. Each walk uses the boundaries as already updated by the earlier walks of the same lap. - Using
<in the loop condition. A last row or column hastop === bottomorleft === right. With<the loop would skip it.
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]]gives[1, 2, 3].[[1, 2], [3, 4]]gives[1, 2, 4, 3].[[5]]gives[5].
