Start learning free

LESSON 50 OF 314 · MATRIX

Spiral Matrix in TypeScript: Walking Four Shrinking Boundaries

Practice O(m*n) Read the full explanation

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

Return an array 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

    TYPESCRIPT · MATRIX

    Spiral Matrix in TypeScript, explained

    Problem overview

    The method spiralOrder receives a matrix of numbers with m rows and n columns, and returns all 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 exactly once. The algorithm must run in O(m * n) time.

    For this matrix:

    [1, 2, 3, 4]
    [5, 6, 7, 8]
    [9, 10, 11, 12]
    

    the answer is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]. The outside gives 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, and what is left inside is a single row, 6 and 7.

    Approach: four boundaries that move inward

    There is no formula for the position of the k-th element, and tracking a direction with turns and "already visited" marks is fiddly. A simpler idea is to keep four numbers that describe the part of the matrix not visited yet: top and bottom are its first and last rows, left and right its first and last columns.

    One lap of a while loop walks the four sides of that part, and each finished side moves its boundary one step inward: after the top row, top goes down by one; after the right column, right goes left by one; and so on. The loop ends when a pair of boundaries crosses, which means nothing is left.

    Each element is pushed once, so the time is proportional to the number of elements.

    Step by step

    1. Create result, an empty number[], to collect elements in the order the spiral reaches them.
    2. Set the row boundaries: top is 0 and bottom is matrix.length - 1.
    3. Set the column boundaries: left is 0 and right is 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. While neither pair has crossed, some elements remain.
    5. Walk the top row from left to right, both included, pushing matrix[top][col].
    6. Move top down. Doing it right away keeps the top-right corner from being visited again by the next walk.
    7. Walk the right column from the new top to bottom, pushing matrix[row][right].
    8. Move right one column to the left.
    9. Walk the bottom row only if top <= bottom. When just one row was left, it was walked as the top row, and top has passed bottom. Walking it back would repeat its elements. The walk goes from right down to left, then bottom moves up.
    10. Walk the left column only if left <= right, for the same reason when one column was left. It goes from bottom up to top, then left moves right.
    11. Return result.

    The solution in TypeScript

    class Solution {
        spiralOrder(matrix: number[][]): number[] {
            let result: number[] = [];
            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 TypeScript details:

    • Several variables in one let. let top = 0, bottom = matrix.length - 1; declares two variables. Both are inferred as number.
    • matrix[row][col] is row first. The first index picks the row (an inner array), the second picks the column inside it. Mixing them up reads the transposed matrix.
    • The annotation number[] on result tells the compiler what the array will hold. It checks nothing at run time, since types are erased when the code is compiled to JavaScript.
    • let for the boundaries. They change on every lap, so const would not allow top++.

    Complexity

    Time: O(m * n). Every element is pushed exactly once, and the guards make sure no side is walked twice. The loop work is proportional to the number of elements.

    Space: O(1) beyond the output. The four boundaries and the loop counters are constant. The returned array holds m * n numbers, which is the answer itself.

    Edge cases and common mistakes

    • A single row. For [[1, 2, 3]] the top walk collects all three, then top passes bottom, so the bottom walk is skipped. Without the first guard the same row would be added again: the unguarded version returns [1, 2, 3, 2, 1].
    • A single column. For [[3], [2], [1]] the answer is [3, 2, 1]. After the right column, right is below left, and the second guard skips the walk up. The unguarded version returns [3, 2, 1, 2].
    • Moving a boundary too late. If top is not increased before the right-column walk, the top-right corner is added twice.
    • Using < instead of <=. The loop and the walks include both ends. A final single cell, such as the 5 in the middle of a 3 by 3 matrix, would be skipped with a strict comparison.
    • Swapped sizes. The row count is matrix.length and the column count is matrix[0].length. Swapping them makes the boundaries point outside the matrix on any non-square input.

    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, 4]] gives [1, 2, 4, 3].
    • [[1]] gives [1].
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free