Spiral Matrix

Pattern: Matrix traversal

medium

Read the outer ring clockwise, then the next ring inside it, and so on. Four boundaries, top, bottom, left and right, shrink by one after each side is read.

The problem

Given a matrix with m rows and n columns, return all its values in spiral order: along the top row to the right, down the right column, along the bottom row to the left, up the left column, and then the same for the ring inside. For example, [[1, 2, 3], [4, 5, 6], [7, 8, 9]] gives [1, 2, 3, 6, 9, 8, 7, 4, 5].

The function name spiralOrder matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Which rows and columns are still unread after you finish the outer ring?
  • After the top row and right column are read, when is there no bottom row left to read?
  • What happens with a single row or a single column?

Hints

    Brute force, and why it fails

    Walk cell by cell with a direction, and turn right whenever the next cell is outside the matrix or already visited. That needs an extra m × n grid of visited marks. The boundary method visits the same cells in the same order with O(1) extra memory.

    The key insight

    The unread cells always form a rectangle. Reading one side of it and shrinking that side keeps it a rectangle, so four numbers describe everything that is left.

    Dry run

    1 2 3 40top
    5 6 7 81 
    9 10 11 122bottom
    left0
    right3
    out

    The matrix has rows 1 2 3 4, 5 6 7 8 and 9 10 11 12. Start with top = 0, bottom = 2, left = 0 and right = 3.

    Step 1 of 4

    The plan

    top = 0, bottom = m - 1, left = 0, right = n - 1
    while top <= bottom and left <= right:
        for c from left to right: add matrix[top][c]
        top = top + 1
        for r from top to bottom: add matrix[r][right]
        right = right - 1
        if top <= bottom:
            for c from right down to left: add matrix[bottom][c]
            bottom = bottom - 1
        if left <= right:
            for r from bottom down to top: add matrix[r][left]
            left = left + 1
    

    Complexity

    Time
    O(m × n)
    Space
    O(1)

    Every cell is read exactly once. Apart from the output list, only the four boundaries are stored.

    Edge cases

    • One cell: [[7]] gives [7].
    • One row, such as [[1, 2, 3, 4]]: only the top row is read, and both checks stop the rest.
    • One column, such as [[1], [2], [3]]: the top cell, then the rest of the right column.
    • Tall or wide rectangles: the inner rectangle ends as one row or one column, never as a square.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> out = new ArrayList<>();
            int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
            while (top <= bottom && left <= right) {
                for (int c = left; c <= right; c++) out.add(matrix[top][c]);          // top row, left to right
                top++;
                for (int r = top; r <= bottom; r++) out.add(matrix[r][right]);        // right column, downwards
                right--;
                if (top <= bottom) {
                    for (int c = right; c >= left; c--) out.add(matrix[bottom][c]);   // bottom row, right to left
                    bottom--;
                }
                if (left <= right) {
                    for (int r = bottom; r >= top; r--) out.add(matrix[r][left]);     // left column, upwards
                    left++;
                }
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> out;
            int top = 0, bottom = static_cast<int>(matrix.size()) - 1;
            int left = 0, right = static_cast<int>(matrix[0].size()) - 1;
            while (top <= bottom && left <= right) {
                for (int c = left; c <= right; c++) out.push_back(matrix[top][c]);          // top row
                top++;
                for (int r = top; r <= bottom; r++) out.push_back(matrix[r][right]);        // right column
                right--;
                if (top <= bottom) {
                    for (int c = right; c >= left; c--) out.push_back(matrix[bottom][c]);   // bottom row
                    bottom--;
                }
                if (left <= right) {
                    for (int r = bottom; r >= top; r--) out.push_back(matrix[r][left]);     // left column
                    left++;
                }
            }
            return out;
        }
    };

    Python

    class Solution:
        def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
            out = []
            top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
            while top <= bottom and left <= right:
                for c in range(left, right + 1):              # top row, left to right
                    out.append(matrix[top][c])
                top += 1
                for r in range(top, bottom + 1):              # right column, downwards
                    out.append(matrix[r][right])
                right -= 1
                if top <= bottom:
                    for c in range(right, left - 1, -1):      # bottom row, right to left
                        out.append(matrix[bottom][c])
                    bottom -= 1
                if left <= right:
                    for r in range(bottom, top - 1, -1):      # left column, upwards
                        out.append(matrix[r][left])
                    left += 1
            return out

    Common mistakes

    • Dropping the two if checks, so the middle row of a 3 × 4 matrix is read forwards and then backwards.
    • Moving a boundary before reading its side, which skips the corner cells.
    • Using the row count for both directions in a matrix that is not square.

    Similar problems