Skip to main content
LeetCode 54, Medium. Topics: Array, Matrix, Simulation. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 14 parametrized pytest cases, and a playground notebook:

Problem

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

Examples

<img alt="" src=“https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg” style=“width: 242px; height: 242px;” />
<img alt="" src=“https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg” style=“width: 322px; height: 242px;” />

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Grind 75, Grind, Blind 75, NeetCode 150, NeetCode 250, NeetCode All, AlgoMaster 75.
Last modified on August 25, 2026