Blind 75
69 / 75Free practice

Spiral Matrix

Medium · Matrices

Jump to code

Return the values of a rectangular matrix in clockwise spiral order, starting at the top-left.

Examples

Example 1

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

Output: [1,2,3,6,9,8,7,4,5]

Example 2

matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Constraints

  • 1 <= matrix.length, matrix[i].length <= 10
  • -100 <= matrix[i][j] <= 100
Need a hint?

Shrink four boundaries after traversing each outer layer.

Asked in real interviews

Candidates reported versions of Spiral Matrix from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    [
      1,
      2,
      3
    ],
    [
      4,
      5,
      6
    ],
    [
      7,
      8,
      9
    ]
  ]
]
Expected
[
  1,
  2,
  3,
  6,
  9,
  8,
  7,
  4,
  5
]
Case 2
Input
[
  [
    [
      1,
      2,
      3,
      4
    ],
    [
      5,
      6,
      7,
      8
    ],
    [
      9,
      10,
      11,
      12
    ]
  ]
]
Expected
[
  1,
  2,
  3,
  4,
  8,
  12,
  11,
  10,
  9,
  5,
  6,
  7
]
Case 3
Input
[
  [
    [
      1
    ]
  ]
]
Expected
[
  1
]
Case 4
Input
[
  [
    [
      1,
      2,
      3,
      4
    ]
  ]
]
Expected
[
  1,
  2,
  3,
  4
]
Case 5
Input
[
  [
    [
      1
    ],
    [
      2
    ],
    [
      3
    ],
    [
      4
    ]
  ]
]
Expected
[
  1,
  2,
  3,
  4
]

Drafts are saved per language in this browser when storage is available.