Back to Practice Dashboard
Top 150 InterviewEasy
Spiral Matrix
Learn how to solve the 'Spiral Matrix' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Easy
Given an m x n matrix, return all elements of the matrix in spiral order.
Implement a function spiralOrder(matrix: list) -> list that returns the elements in spiral order.
Constraints
- •m == matrix.length
- •n == matrix[i].length
- •1 <= m, n <= 10
- •-100 <= matrix[i][j] <= 100
Examples
Example 1
Input
[[1,2,3],[4,5,6],[7,8,9]]
Output
[1,2,3,6,9,8,7,4,5]
Explanation
Spiral order: right across top [1,2,3], down right side [6,9], left across bottom [8,7], up left side [4], then center [5].
Example 2
Input
[[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]
Explanation
Spiral order through a 3x4 matrix.
Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.