FastPrepSpiral Matrix Traversal
Problems/Spiral Matrix Traversal

Spiral Matrix Traversal

ByteDance logoByteDance● MediumINTERNPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report directly names the canonical Spiral Matrix exercise. The judged core preserves that task at about 95%; the no-mutation, constant-auxiliary-traversal-state choice is part of the authored practice contract.

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

  • Binary Tree Target-Sum PathsPHONE SCREEN · Seen Nov 2026
  • Longest Increasing SubsequencePHONE SCREEN · Seen Nov 2026
  • Alien DictionaryPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
All ByteDance interview questionsSee ByteDance hiring insights
Saved
class Solution {
    public int[] spiralTraversal(int[][] matrix) {
        // Write your code here.
    }

}
Checking account…