Facebook PixelSpiral Matrix — Coding Practice
Spiral MatrixMedium

Spiral Matrix

Medium 13.8k49% acceptance
ArrayMatrixSimulation

Given an m × n matrix, return all of its elements in spiral order: start at the top-left corner and walk right across the top row, then down the right column, then left along the bottom row, then up the left column, spiraling inward until every element has been visited.

Example 1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Right across the top, down the right side, left along the bottom, up the left side, then the center.
Example 2
Input: 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]
Example 3
Input: matrix = [[7]]
Output: [7]
Constraints
  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 10
  • -100 ≤ matrix[i][j] ≤ 100
Asked atMicrosoftAmazonGoogleApple
JavaScript
Loading editor…
Case 1
[[1,2,3],[4,5,6],[7,8,9]]
expected: [1,2,3,6,9,8,7,4,5]
Case 2
[[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
[[7]]
expected: [7]
Case 4
[[1,2],[3,4]]
expected: [1,2,4,3]
Case 5
[[1],[2],[3],[4]]
expected: [1,2,3,4]
Case 6
[[1,2,3,4]]
expected: [1,2,3,4]