Problem overview
The function spiralOrder receives a matrix as an Array<IntArray> with m rows and n columns, and returns a List<Int> with every element 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 the part that is left inside, until every element has been visited exactly once.
For the 3 by 3 matrix with rows 1 2 3, 4 5 6, 7 8 9, the result is [1, 2, 3, 6, 9, 8, 7, 4, 5]: the outer ring, then the single element 5 in the middle. For a 3 by 4 matrix with rows 1 2 3 4, 5 6 7 8, 9 10 11 12, the result is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]. The inside is a single row, 6 and 7, read from left to right.
Approach
One option is to mark visited cells and turn right whenever the next cell is outside the matrix or already visited. That needs a second grid of flags, or a change to the matrix. A neater way is to track which part of the matrix is still unvisited with four boundaries:
topandbottom: the first and last unvisited rows;leftandright: the first and last unvisited columns.
Each lap of a while loop walks once around the unvisited part, side by side, and every finished side moves its boundary one step inward. The loop ends when a pair of boundaries crosses. Every cell is added once, so the time is O(m * n), and apart from the result list, only four integers are needed.
Step by step
- Create the output.
val result = mutableListOf<Int>()collects elements in the order they are visited. It is aval: the name never changes, but the list grows. - Row boundaries.
topstarts at 0 andbottomatmatrix.size - 1. They arevars because they move. - Column boundaries.
leftstarts at 0 andrightatmatrix[0].size - 1. Every row has the same length, so the first row tells how many columns there are. - The lap loop.
while (top <= bottom && left <= right): while neither pair has crossed, something is unvisited. - Top side. Walk
coloverleft..rightand addmatrix[top][col]. Then dotop++. Movingtopdown first also stops the top-right corner from being visited again by the next side. - Right side. Walk
rowovertop..bottom(with the newtop) and addmatrix[row][right]. Then doright--. - Bottom side, only if rows remain. Inside
if (top <= bottom), walkcoloverright downTo leftand addmatrix[bottom][col], then dobottom--. When only one row was left, the top side just walked it andtophas passedbottom; walking it back would add its elements a second time. - Left side, only if columns remain. Inside
if (left <= right), walkrowoverbottom downTo topand addmatrix[row][left], then doleft++. The same reasoning applies to a single remaining column. - Return
resultafter the loop.
On the 3 by 4 example, the boundaries after each lap (top, bottom, left, right) are 1, 1, 1, 2 after the first lap and 2, 1, 2, 1 after the second. The second lap walks the middle row once, and then top is past bottom, so the loop ends.
The solution in Kotlin
class Solution {
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
val result = mutableListOf<Int>()
var top = 0
var bottom = matrix.size - 1
var left = 0
var right = matrix[0].size - 1
while (top <= bottom && left <= right) {
for (col in left..right) {
result.add(matrix[top][col])
}
top++
for (row in top..bottom) {
result.add(matrix[row][right])
}
right--
if (top <= bottom) {
for (col in right downTo left) {
result.add(matrix[bottom][col])
}
bottom--
}
if (left <= right) {
for (row in bottom downTo top) {
result.add(matrix[row][left])
}
left++
}
}
return result
}
}
Kotlin details worth knowing:
- Ranges.
left..rightincludes both ends and is empty whenleftis greater thanright, so a loop over it simply does nothing.downToworks the same way going down. The right-side loop relies on this whentophas just moved pastbottom. - Return type.
mutableListOf<Int>()creates aMutableList<Int>, which can be returned where a read-onlyList<Int>is expected. - Increment and decrement.
top++andright--work onvars as statements, as in Java. - Two dimensions.
matrix[top][col]first gets the row array, then the element in it.
Complexity
Time is O(m * n): each element is added once, and the boundary bookkeeping is constant work per side. Extra space is O(1) beyond the result list, which is the required output.
Edge cases and common mistakes
- A single row. For the one-row matrix
[1, 2, 3, 4]the result is[1, 2, 3, 4]. Without theif (top <= bottom)check, the bottom-row walk would run over the same row again and the output would be[1, 2, 3, 4, 3, 2, 1]. - A single column. For the column
3, 2, 1the result is[3, 2, 1]. Without the checks, the output would be[3, 2, 1, 2]. - A 1 by 1 matrix.
[7]gives[7]: the top side adds it, and the other three sides find nothing left. - Updating a boundary too early or too late. Each boundary must move right after its side is done, before the next side reads it.
- Using
<instead of<=. A lap withtop == bottomstill has a row to read, so the comparisons must allow equality.
Testing
Results the solution returns:
[[1,2,3],[4,5,6],[7,8,9]] -> [1, 2, 3, 6, 9, 8, 7, 4, 5]
[[1,2,3,4],[5,6,7,8],[9,10,11,12]] -> [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
[[3],[2],[1]] -> [3, 2, 1]
[[1,2,3,4]] -> [1, 2, 3, 4]
[[1,2],[3,4]] -> [1, 2, 4, 3]
[[7]] -> [7]
