FastPrepSpiral Matrix

Spiral Matrix

Nike, Inc. logoNike, Inc.● MediumFULLTIMEONSITE INTERVIEW

Problem statement

Given a non-empty rectangular integer matrix matrix, return its values in clockwise spiral order.

Start at the top-left cell and move right across the top row. Continue down the right edge, left across the bottom edge, and up the left edge. Repeat with the remaining inner rectangle until every cell has been visited once.

Function

spiralOrder(matrix: int[][]) → int[]

Examples

Example 1

matrix = [[1,2,3],[4,5,6],[7,8,9]]return = [1,2,3,6,9,8,7,4,5]

The outer ring is [1,2,3,6,9,8,7,4]. The remaining center is 5.

Example 2

matrix = [[1,2,3,4],[5,6,7,8]]return = [1,2,3,4,8,7,6,5]

Visit the top row, then the rightmost value of the bottom row, then the remaining bottom-row values from right to left.

Constraints

  • matrix has between 1 and 50 rows.
  • Each row has between 1 and 50 integers.
  • All rows have the same length.
  • Each integer is between -10^4 and 10^4.

More Nike, Inc. problems

See Nike, Inc. hiring insights
Saved
public int[] spiralOrder(int[][] matrix) {
    // write your code here
}
Checking account…