Start learning free

LESSON 332 OF 671 · MATRIX

Spiral Matrix in Java: Four Shrinking Boundaries, O(m * n)

Practice O(m*n) Read the full explanation

You get a grid matrix of integers, with m rows and n columns.

Return an ArrayList of its values in spiral order.

matrix is an array of rows. Each row is an array of integers. Row 0 is the top row. Column 0 is the leftmost column.

The spiral starts at the top-left value and goes clockwise around the edge. It goes right along the top row, then down the right column. Then it goes left along the bottom row and up the left column.

Next, it does the same with the smaller grid inside, and so on. It takes each value exactly once.

 

Example 1:

Input: matrix = [
  [5, 1, 8],
  [0, 3, 2],
  [9, 7, 4]
]
Output: [5, 1, 8, 2, 4, 7, 9, 0, 3]
Explanation: The spiral first goes around the edge:
5, 1 and 8 across the top,
2 and 4 down the right side,
7 and 9 back along the bottom,
0 up the left side.
3 is left in the middle.

Example 2:

Input: matrix = [
  [3, -1, 7],
  [6, 0, 2],
  [1, 5, 9],
  [8, 8, 4]
]
Output: [3, -1, 7, 2, 9, 4, 8, 8, 1, 6, 0, 5]
Explanation: The spiral first goes around the edge:
3, -1 and 7 across the top,
2, 9 and 4 down the right side,
8 and 8 back along the bottom,
1 and 6 up the left side.
Inside, one column is left.
It gives 0, then the 5 below it.

Example 3:

Input: matrix = [
  [-4, 0, 4]
]
Output: [-4, 0, 4]
Explanation: There is only one row.
The spiral goes right along it and stops.
No value is taken twice.

 

Constraints:

  • m and n are each from 1 to 500.
  • Each value is an integer from -1000 to 1000.
  • Negative values and repeats are allowed.

Note:

Your algorithm should run in O(m * n) time: it visits every element once.

STEP 1 OF 19
    Ctrl + Enter to check

    JAVA · MATRIX

    Spiral Matrix in Java, explained

    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:

    • top and bottom, the first and last unvisited rows;
    • left and right, 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

    1. Create result as a List<Integer> holding a new ArrayList.
    2. Row boundaries: top = 0 and bottom = matrix.length - 1, the index of the last row.
    3. Column boundaries: left = 0 and right = matrix[0].length - 1. Every row has the same length, so the first row tells the number of columns.
    4. Loop while top <= bottom && left <= right. As long as neither pair has crossed, some elements remain.
    5. Top side. Walk col from left to right, inclusive, adding matrix[top][col]. Then do top++. Moving top first keeps the top-right corner from being added again by the next side.
    6. Right side. Walk row from top (already moved down) to bottom, adding matrix[row][right]. Then do right--.
    7. Bottom side, only if top <= bottom. If only one row was left, it was just walked as the top row, and top has passed bottom. Walk col from right down to left, adding matrix[bottom][col], then do bottom--.
    8. Left side, only if left <= right. If only one column was left, it was just walked as the right column. Walk row from bottom up to top, adding matrix[row][left], then do left++.
    9. Return result after 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. List and ArrayList live in java.util. In a file of your own you need import java.util.*; at the top.
    • Declared type against created type. The variable has the interface type List<Integer> and holds an ArrayList<>. The empty <> lets the compiler infer Integer from the left side.
    • Autoboxing. result.add(matrix[top][col]) passes an int where a list of Integer expects an object. Java wraps it automatically.
    • Two variables in one declaration. int top = 0, bottom = matrix.length - 1; declares both in one statement, and bottom can already use matrix.
    • 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 the if (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 the if (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.length is the number of rows, and matrix[0].length is 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].
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free