Top 150 InterviewEasy

Spiral Matrix

Detailed guide and Python implementation for the 'Spiral Matrix' problem.

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?
Consider using Math & Geometry-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.