Problem overview
The method spiralOrder receives an int[][] matrix with m rows and n columns and returns a List<Integer> holding all of 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 once.
For [[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 5 in the middle. For the 3 by 4 matrix [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] it is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]. The ring leaves one row, 6 and 7, which is then read left to right.
Approach: walk the sides, move the boundaries
You could track a direction and turn when you hit an edge or a visited cell, which needs a second matrix of visited flags. A simpler way keeps four numbers that mark the part of the matrix not visited yet:
topandbottom, the first and last unvisited rows;leftandright, the first and last unvisited columns.
Each lap of a while loop walks the four sides of that rectangle, and each finished side moves its boundary one step inward. When the boundaries cross, nothing is left. Every element is added exactly once, so the time is O(m * n), and the only extra memory besides the result is four integers.
The one subtlety is that a rectangle that is one row or one column wide has fewer than four sides. After the top row and the right column have been walked, the code must check that a bottom row and a left column still exist before walking them. Otherwise a single row would be read forwards and then backwards.
Step by step
- Create
resultas aList<Integer>holding a newArrayList. - Row boundaries:
top = 0andbottom = matrix.length - 1, the index of the last row. - Column boundaries:
left = 0andright = matrix[0].length - 1. Every row has the same length, so the first row tells the number of columns. - Loop while
top <= bottom && left <= right. As long as neither pair has crossed, some elements remain. - Top side. Walk
colfromlefttoright, inclusive, addingmatrix[top][col]. Then dotop++. Movingtopfirst keeps the top-right corner from being added again by the next side. - Right side. Walk
rowfromtop(already moved down) tobottom, addingmatrix[row][right]. Then doright--. - Bottom side, only if
top <= bottom. If only one row was left, it was just walked as the top row, andtophas passedbottom. Walkcolfromrightdown toleft, addingmatrix[bottom][col], then dobottom--. - Left side, only if
left <= right. If only one column was left, it was just walked as the right column. Walkrowfrombottomup totop, addingmatrix[row][left], then doleft++. - Return
resultafter the loop.
The solution in Java
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int col = left; col <= right; col++) {
result.add(matrix[top][col]);
}
top++;
for (int row = top; row <= bottom; row++) {
result.add(matrix[row][right]);
}
right--;
if (top <= bottom) {
for (int col = right; col >= left; col--) {
result.add(matrix[bottom][col]);
}
bottom--;
}
if (left <= right) {
for (int row = bottom; row >= top; row--) {
result.add(matrix[row][left]);
}
left++;
}
}
return result;
}
}
The Java details worth a closer look:
- Imports.
ListandArrayListlive injava.util. In a file of your own you needimport java.util.*;at the top. - Declared type against created type. The variable has the interface type
List<Integer>and holds anArrayList<>. The empty<>lets the compiler inferIntegerfrom the left side. - Autoboxing.
result.add(matrix[top][col])passes anintwhere a list ofIntegerexpects an object. Java wraps it automatically. - Two variables in one declaration.
int top = 0, bottom = matrix.length - 1;declares both in one statement, andbottomcan already usematrix. - Inclusive loops. The loops use
<=and>=because both boundaries are real rows or columns still to visit. A strict comparison would skip the last element of each side.
Complexity
Time: O(m * n). Each element is added exactly once, and the boundary checks add only constant work per lap.
Space: O(1) extra. The list holds the m * n answers, which the method has to return anyway. Besides it, only top, bottom, left, right and the loop variables exist.
Edge cases and common mistakes
- A single row.
[[1, 2, 3]]gives[1, 2, 3]. Without theif (top <= bottom)guard, the bottom side would walk the same row again and the list would be[1, 2, 3, 2, 1]. - A single column.
[[3], [2], [1]]gives[3, 2, 1]. Without theif (left <= right)guard, the left side would add 2 once more and the list would be[3, 2, 1, 2]. - Both guards missing on the 3 by 4 example. The list gets a repeated 6 at its end:
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6]. - Moving a boundary too late. If
top++comes after the right side, the right column starts at the top-right corner and adds it a second time. - Rectangles that aren't square. A 4 by 2 matrix
[[1, 2], [3, 4], [5, 6], [7, 8]]gives[1, 2, 4, 6, 8, 7, 5, 3]. The two columns run out before the rows do, and the loop ends cleanly. - Using the wrong length.
matrix.lengthis the number of rows, andmatrix[0].lengthis the number of columns. Mixing them up fails on any matrix that isn't square.
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], [5, 6], [7, 8]]gives[1, 2, 4, 6, 8, 7, 5, 3].
