Practice Problem

Spiral Matrix

Difficulty: Medium

Return all elements of an m x n matrix in spiral order, traversing from the outer boundary inward.

Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

Examples

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Explanation: Spiral starting from top-left going clockwise:
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5

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

Expected Complexity

  • Time: O(m * n)
  • Space: O(1) excluding the output array
MEDIUM
Arrays
Matrix Algorithms
Matrix Traversal
Spiral Order
Simulation
Intermediate

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium