Start learning free

LESSON 50 OF 314 · MATRIX

Spiral Matrix in JavaScript: O(m * n) with Four 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

    JAVASCRIPT · MATRIX

    Spiral Matrix in JavaScript, explained

    Problem overview

    The method spiralOrder(matrix) receives a matrix with m rows and n columns, an array of rows where each row is an array of integers. It returns one array with every element in spiral order. The spiral starts at the top-left corner and goes clockwise around the outside: along the top row, down the right column, back along the bottom row and up the left column. Then it repeats on the part inside, until every element has been visited once.

    For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the answer is [1, 2, 3, 6, 9, 8, 7, 4, 5]. The outer ring gives 1, 2, 3, 6, 9, 8, 7, 4, and only 5 is left in the middle. The matrix doesn't have to be square: [[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].

    Approach: shrink four boundaries

    You can't simply loop over rows and columns, because the direction changes at each corner. You could instead mark visited cells and turn right whenever the next cell is outside the matrix or already visited. That works, but it needs an extra grid of marks. A simpler way tracks which part of the matrix is still unvisited with four numbers:

    • top and bottom: the first and last rows not yet visited;
    • left and right: the first and last columns not yet visited.

    One lap of the loop walks once around that part. After each side is finished, its boundary moves one step inward: top goes down after the top row, right goes left after the right column, and so on. The loop runs while top <= bottom and left <= right, which means some cells are still left. Each element is pushed exactly once, so the running time is O(m * n).

    The delicate part is the end of the spiral. When one row or one column is all that remains, the "back along the bottom" or "back up the left" walk would visit the same cells a second time. Two if checks prevent that.

    Here are the laps on two of the lesson's examples:

    MatrixElements added in the laptop, bottom, left, right afterwards
    3 by 31,2,3,6,9,8,7,41, 1, 1, 1
    3 by 352, 1, 1, 0
    3 by 41,2,3,4,8,12,11,10,9,51, 1, 1, 2
    3 by 46,72, 1, 2, 1

    In every case the boundaries cross at the end, so the loop condition stops it.

    Step by step

    1. Start with an empty result array that will collect the elements in visiting order.
    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. All rows have the same length, so the first row tells the column count.
    4. Loop while both pairs of boundaries are still in order. Each pass walks one ring.
    5. Walk the top row from left to right, 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], then move right one column left.
    8. Check that a bottom row is left with top <= bottom. If only one row remained, it was just walked as the top row, and walking it backwards would repeat its elements.
    9. Walk the bottom row backwards from right down to left, then move bottom up.
    10. Check that a left column is left with left <= right, for the same reason: a single remaining column was already walked as the right column.
    11. Walk the left column upwards from bottom to top, then move left one column right.
    12. Return result after the loop.

    The solution in JavaScript

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

    • Several declarations on one line. let top = 0, bottom = matrix.length - 1; declares two variables with one let. Both are reassigned later, so const would not work.
    • Matrices are arrays of arrays. matrix[top][col] first picks a row, then a cell in it. matrix[0].length is the number of columns, and matrix.length the number of rows.
    • Loops that count down. The bottom and left walks use col-- and row--. If right or bottom has already crossed its partner, the loop condition is false at once and the loop body never runs.
    • Reading outside an array doesn't throw. In JavaScript matrix[5] on a three-row matrix is undefined, but matrix[5][0] throws a TypeError. The boundary checks keep every access inside the matrix.

    Complexity

    Time: O(m * n). Every cell is pushed to result exactly once, and the loop condition and checks cost constant time per lap. The number of laps is at most about half of the smaller dimension.

    Space: O(1) extra, not counting result, which holds all m * n elements. The function keeps only the four boundaries and the loop counters.

    Edge cases and common mistakes

    • A single row. [[1, 2, 3]] must return [1, 2, 3]. Without the top <= bottom check, the bottom walk would add the same row again and give [1, 2, 3, 2, 1].
    • A single column. [[3], [2], [1]] returns [3, 2, 1]. Without the left <= right check, the left walk would add elements a second time: a version with both checks removed returns [3, 2, 1, 2].
    • A leftover row in the middle. For the 3 by 4 example, the second lap holds a single row, 6 and 7. Without the checks the result ends with a stray 6: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6].
    • A single element. [[5]] gives [5].
    • Moving a boundary too late. If top is not moved right after the top row, the right-column walk starts on the corner again and pushes it twice.
    • Using the wrong boundary for the walk. The right column runs from top to bottom, the bottom row from right to left. Each walk uses the boundaries as already updated by the earlier walks of the same lap.
    • Using < in the loop condition. A last row or column has top === bottom or left === right. With < the loop would skip it.

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