Spiral Matrix
Medium · Matrix · Array · Matrix · Simulation
Problem
Given an m x n matrix, return all its elements read in spiral order — left across the top, down the right side, back across the bottom, up the left, then inward.
Examples
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]
Around the rim, then the centre.
Input: matrix = [[1,2,3,4]] Output: [1,2,3,4]
A single row.
Constraints
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
Approaches
- Peel the top row and rotate — time O(m · n), space O(m · n)
Related problems
Start free on Cariara · Coding problems · System design studio