Start learning free

LESSON 50 OF 314 · MATRIX

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

    SCALA · MATRIX

    Spiral Matrix in Scala, explained

    Problem overview

    The method spiralOrder takes a matrix as an Array[Array[Int]] with m rows and n columns, and returns an ArrayBuffer[Int] holding all of its elements in spiral order. The spiral starts at the top-left corner and goes clockwise: along the top row, down the right column, back along the bottom row, and up the left column. Then it repeats on what is left inside, until every element has been visited exactly once.

    For this matrix:

    1 2 3
    4 5 6
    7 8 9
    

    the result is [1,2,3,6,9,8,7,4,5]: the outer ring clockwise, then the single cell 5 in the middle. For the 3 by 4 matrix with rows 1,2,3,4, 5,6,7,8 and 9,10,11,12 the result is [1,2,3,4,8,12,11,10,9,5,6,7]. The second lap there is a single row, 6 and 7.

    Approach: walk the sides and move the boundaries inward

    Computing each element's position directly is awkward, because the direction changes at every corner. A cleaner way is to remember which part of the matrix has not been visited yet. Four variables describe it: top and bottom are its first and last unvisited rows, and left and right are its first and last unvisited columns.

    One lap walks the four sides of that rectangle. After each side is finished, the matching boundary moves one step inward, so the next lap works on a smaller rectangle. When a pair of boundaries crosses, nothing is left and the loop stops. Each element is added once, so the work is proportional to the number of elements.

    The tricky part is the end of the spiral. When the rectangle is a single row or a single column, the bottom side or the left side would walk the same elements a second time. The two if checks in the solution prevent that.

    Step by step

    1. Create result as an empty ArrayBuffer[Int] in a val. It collects the elements in visiting order, and the val is fine because the buffer itself changes, not the name.
    2. Row boundaries: top starts at 0 and bottom at matrix.length - 1. They are vars because they move.
    3. Column boundaries: left starts at 0 and right at matrix(0).length - 1. Every row has the same length, so the first row says how many columns there are.
    4. Loop while top <= bottom && left <= right. As long as neither pair has crossed, some elements remain.
    5. Top side: for (col <- left to right) appends matrix(top)(col) to result with +=.
    6. Move top down. The top row is done. Doing it right here also stops the top-right corner from being read again by the next side.
    7. Right side: for (row <- top to bottom) appends matrix(row)(right).
    8. Move right left. The right column is done.
    9. Guard the bottom side with if (top <= bottom). If only one row was left, the top-side loop already read it, and top has moved past bottom. Reading it backwards would add its elements twice.
    10. Bottom side: for (col <- right to left by -1) appends matrix(bottom)(col), then bottom moves up.
    11. Guard the left side with if (left <= right). With a single column left, the right side already covered it (the 3 by 1 example), and walking up would repeat it.
    12. Left side: for (row <- bottom to top by -1) appends matrix(row)(left), then left moves right. That ends the lap.
    13. Return result.

    The solution in Scala

    class Solution {
        def spiralOrder(matrix: Array[Array[Int]]): ArrayBuffer[Int] = {
            val result = ArrayBuffer[Int]()
            var top = 0
            var bottom = matrix.length - 1
            var left = 0
            var right = matrix(0).length - 1
            while (top <= bottom && left <= right) {
                for (col <- left to right) {
                    result += matrix(top)(col)
                }
                top += 1
                for (row <- top to bottom) {
                    result += matrix(row)(right)
                }
                right -= 1
                if (top <= bottom) {
                    for (col <- right to left by -1) {
                        result += matrix(bottom)(col)
                    }
                    bottom -= 1
                }
                if (left <= right) {
                    for (row <- bottom to top by -1) {
                        result += matrix(row)(left)
                    }
                    left += 1
                }
            }
            return result
        }
    }
    

    Scala details worth knowing:

    • ArrayBuffer needs an import. It lives in scala.collection.mutable, so a standalone file that uses it needs import scala.collection.mutable.ArrayBuffer at the top. Unlike an Array, an ArrayBuffer grows, and += appends one element.
    • to includes its end, and an empty range is fine. left to right covers both columns. When the start is past the end, as in 3 to 2, the range is empty and the loop body never runs. The solution relies on this when the rectangle has run out of rows or columns. A range that counts down needs by -1: 2 to 0 by -1 gives 2, 1, 0, but 2 to 0 alone is empty.
    • The loop bounds are read once. A for over a range evaluates left to right when the loop starts. Changing top or right inside the loop wouldn't change the range already in progress, which is why the code moves them after each loop.
    • Explicit return. The reference ends with return result. In Scala the last expression alone, result, would give the same value, and return is rarely needed, but it is correct here.
    • The result type. The method returns an ArrayBuffer[Int], not an Array. Printing it with mkString("[", ",", "]") gives the format of the examples.

    Complexity

    Time: O(m * n). Every element is appended exactly once, and the loops do a constant amount of work apart from those appends. The boundary checks add only a few operations per lap.

    Space: O(1) extra. Besides the returned buffer, which holds all m * n elements, only the four boundary variables and the loop counters are stored.

    Edge cases and common mistakes

    • A single row. [[1,2,3]] gives [1,2,3]. The top side reads everything, top moves past bottom, and the two guards skip the remaining sides.
    • A single column. [[3],[2],[1]] gives [3,2,1]. The top side reads 3, and the right side reads 2 and 1. Then left <= right is false, so nothing is read twice.
    • A single element. [[4]] gives [4].
    • A tall matrix. The 4 by 2 matrix with rows 1,2, 3,4, 5,6 and 7,8 gives [1,2,4,6,8,7,5,3]. The left side stops before the top row, so 1 isn't visited again.
    • Dropping the two if guards. On any matrix whose last lap is a single row or column, elements would appear twice.
    • Using until in place of to. The boundaries are inclusive indices of rows and columns, so until would leave out the last one.
    • Forgetting by -1. right to left is empty when right is bigger than left, so the bottom and left sides would silently add nothing.
    • Empty input. The lesson guarantees at least one row and one column. matrix(0) would throw an exception on an array with no rows.

    Testing

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