Start learning free

LESSON 50 OF 314 · MATRIX

Spiral Matrix in Kotlin: 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 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

    KOTLIN · MATRIX

    Spiral Matrix in Kotlin, explained

    Problem overview

    The function spiralOrder receives a matrix as an Array<IntArray> with m rows and n columns, and returns a List<Int> with every element 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 the part that is left inside, until every element has been visited exactly once.

    For the 3 by 3 matrix with rows 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 element 5 in the middle. For a 3 by 4 matrix with rows 1 2 3 4, 5 6 7 8, 9 10 11 12, the result is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]. The inside is a single row, 6 and 7, read from left to right.

    Approach

    One option is to mark visited cells and turn right whenever the next cell is outside the matrix or already visited. That needs a second grid of flags, or a change to the matrix. A neater way is to track which part of the matrix is still unvisited with four boundaries:

    • 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 once around the unvisited part, side by side, and every finished side moves its boundary one step inward. The loop ends when a pair of boundaries crosses. Every cell is added once, so the time is O(m * n), and apart from the result list, only four integers are needed.

    Step by step

    1. Create the output. val result = mutableListOf<Int>() collects elements in the order they are visited. It is a val: the name never changes, but the list grows.
    2. Row boundaries. top starts at 0 and bottom at matrix.size - 1. They are vars because they move.
    3. Column boundaries. left starts at 0 and right at matrix[0].size - 1. Every row has the same length, so the first row tells how many columns there are.
    4. The lap loop. while (top <= bottom && left <= right): while neither pair has crossed, something is unvisited.
    5. Top side. Walk col over left..right and add matrix[top][col]. Then do top++. Moving top down first also stops the top-right corner from being visited again by the next side.
    6. Right side. Walk row over top..bottom (with the new top) and add matrix[row][right]. Then do right--.
    7. Bottom side, only if rows remain. Inside if (top <= bottom), walk col over right downTo left and add matrix[bottom][col], then do bottom--. When only one row was left, the top side just walked it and top has passed bottom; walking it back would add its elements a second time.
    8. Left side, only if columns remain. Inside if (left <= right), walk row over bottom downTo top and add matrix[row][left], then do left++. The same reasoning applies to a single remaining column.
    9. Return result after the loop.

    On the 3 by 4 example, the boundaries after each lap (top, bottom, left, right) are 1, 1, 1, 2 after the first lap and 2, 1, 2, 1 after the second. The second lap walks the middle row once, and then top is past bottom, so the loop ends.

    The solution in Kotlin

    class Solution {
        fun spiralOrder(matrix: Array<IntArray>): List<Int> {
            val result = mutableListOf<Int>()
            var top = 0
            var bottom = matrix.size - 1
            var left = 0
            var right = matrix[0].size - 1
            while (top <= bottom && left <= right) {
                for (col in left..right) {
                    result.add(matrix[top][col])
                }
                top++
                for (row in top..bottom) {
                    result.add(matrix[row][right])
                }
                right--
                if (top <= bottom) {
                    for (col in right downTo left) {
                        result.add(matrix[bottom][col])
                    }
                    bottom--
                }
                if (left <= right) {
                    for (row in bottom downTo top) {
                        result.add(matrix[row][left])
                    }
                    left++
                }
            }
            return result
        }
    }
    

    Kotlin details worth knowing:

    • Ranges. left..right includes both ends and is empty when left is greater than right, so a loop over it simply does nothing. downTo works the same way going down. The right-side loop relies on this when top has just moved past bottom.
    • Return type. mutableListOf<Int>() creates a MutableList<Int>, which can be returned where a read-only List<Int> is expected.
    • Increment and decrement. top++ and right-- work on vars as statements, as in Java.
    • Two dimensions. matrix[top][col] first gets the row array, then the element in it.

    Complexity

    Time is O(m * n): each element is added once, and the boundary bookkeeping is constant work per side. Extra space is O(1) beyond the result list, which is the required output.

    Edge cases and common mistakes

    • A single row. For the one-row matrix [1, 2, 3, 4] the result is [1, 2, 3, 4]. Without the if (top <= bottom) check, the bottom-row walk would run over the same row again and the output would be [1, 2, 3, 4, 3, 2, 1].
    • A single column. For the column 3, 2, 1 the result is [3, 2, 1]. Without the checks, the output would be [3, 2, 1, 2].
    • A 1 by 1 matrix. [7] gives [7]: the top side adds it, and the other three sides find nothing left.
    • Updating a boundary too early or too late. Each boundary must move right after its side is done, before the next side reads it.
    • Using < instead of <=. A lap with top == bottom still has a row to read, so the comparisons must allow equality.

    Testing

    Results the solution returns:

    [[1,2,3],[4,5,6],[7,8,9]]        -> [1, 2, 3, 6, 9, 8, 7, 4, 5]
    [[1,2,3,4],[5,6,7,8],[9,10,11,12]] -> [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
    [[3],[2],[1]]                    -> [3, 2, 1]
    [[1,2,3,4]]                      -> [1, 2, 3, 4]
    [[1,2],[3,4]]                    -> [1, 2, 4, 3]
    [[7]]                            -> [7]
    
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free