LeetCode 54: Spiral Matrix — Python Solution

Solve LeetCode 54: Spiral Matrix in Python with a shrinking boundaries approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicMatrix
Reusable patternshrinking boundaries
ComplexityO(mn) time and O(1) extra space excluding output

What the problem is testing

Traverse top, right, bottom, and left boundaries, then shrink them while checking whether each boundary still exists.

Algorithm

  1. Traverse top, right, bottom, and left boundaries, then shrink them while checking whether each boundary still exists.
  2. Maintain this invariant: All cells outside the current boundaries have been emitted exactly once.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def spiralOrder(self, matrix):
        if not matrix: return []
        top, bottom, left, right, answer = 0, len(matrix) - 1, 0, len(matrix[0]) - 1, []
        while top <= bottom and left <= right:
            answer.extend(matrix[top][left:right + 1]); top += 1
            for r in range(top, bottom + 1): answer.append(matrix[r][right])
            right -= 1
            if top <= bottom:
                answer.extend(reversed(matrix[bottom][left:right + 1])); bottom -= 1
            if left <= right:
                for r in range(bottom, top - 1, -1): answer.append(matrix[r][left])
                left += 1
        return answer

Why this is correct

The proof follows the maintained state: All cells outside the current boundaries have been emitted exactly once. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(mn) time and O(1) extra space excluding output. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Single remaining rows or columns must not be traversed twice.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 36. Valid Sudoku · Next: 48. Rotate Image