Read-only web browser

Solutions

Browse the interview solutions folder with syntax highlighting.

spiral-matrix.py

math-geometry/spiral-matrix.py · Python · 877 B · 2026-05-09 19:22

Back to folder
# Proceed in layers. Set top, bottom, left and right boundaries, then move inwards.
# math

# O(m*n) time, O(1) space
def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
    if not matrix or not matrix[0]:
        return []

    m = len(matrix)
    n = len(matrix[0])
    top, bottom, left, right = 0, m-1, 0, n-1

    res = []

    while top <= bottom and left <= right:

        for i in range(left, right + 1):
            res.append(matrix[top][i])

        top += 1
        for i in range(top, bottom + 1):
            res.append(matrix[i][right])

        right -= 1
        if top <= bottom:
            for i in range(right, left - 1, -1):
                res.append(matrix[bottom][i])

        bottom -= 1
        if left <= right:
            for i in range(bottom, top - 1, -1):
                res.append(matrix[i][left])

        left += 1

    return res