FastPrepSpiral Matrix Traversal

Spiral Matrix Traversal

ByteDance logoByteDance● MediumINTERNPHONE SCREEN
Learn

Problem statement

You are given a non-empty rectangular integer matrix.

Return all elements in clockwise spiral order, beginning at the top-left corner. Traverse the top edge, right edge, bottom edge in reverse, and left edge in reverse, then repeat on the remaining inner rectangle.

Function

spiralTraversal(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]

The two-row matrix is consumed entirely by its outer ring.

Constraints

  • 1 <= matrix.length, matrix[i].length <= 1000
  • All rows have the same length.
  • The matrix contains at most 10^5 elements.
  • -10^9 <= matrix[i][j] <= 10^9

More ByteDance problems

See ByteDance hiring insights
public int[] spiralTraversal(int[][] matrix) {
    // Write your code here.
}
matrix[[1,2,3],[4,5,6],[7,8,9]]
expected[1,2,3,6,9,8,7,4,5]
Checking account…