← Back to Leo Academy Masterclass

Problem #54: Spiral Matrix

Medium Matrix

Intuition & Strategy Breakdown

Maintain four boundaries (top, bottom, left, right). Traverse top row left-to-right, right column top-to-bottom, bottom row right-to-left, and left column bottom-to-top while shrinking boundaries.

Python Solution

class Solution:
    def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
        res = []
        left, right = 0, len(matrix[0])
        top, bottom = 0, len(matrix)
        while left < right and top < bottom:
            for i in range(left, right):
                res.append(matrix[top][i])
            top += 1
            for i in range(top, bottom):
                res.append(matrix[i][right - 1])
            right -= 1
            if not (left < right and top < bottom): break
            for i in range(right - 1, left - 1, -1):
                res.append(matrix[bottom - 1][i])
            bottom -= 1
            for i in range(bottom - 1, top - 1, -1):
                res.append(matrix[i][left])
            left += 1
        return res

Java Solution

class Solution {
    public List spiralOrder(int[][] matrix) {
        List res = new ArrayList<>();
        int left = 0, right = matrix[0].length;
        int top = 0, bottom = matrix.length;
        while (left < right && top < bottom) {
            for (int i = left; i < right; i++) res.add(matrix[top][i]);
            top++;
            for (int i = top; i < bottom; i++) res.add(matrix[i][right - 1]);
            right--;
            if (!(left < right && top < bottom)) break;
            for (int i = right - 1; i >= left; i--) res.add(matrix[bottom - 1][i]);
            bottom--;
            for (int i = bottom - 1; i >= top; i--) res.add(matrix[i][left]);
            left++;
        }
        return res;
    }
}
Watch Interactive Video on Leo Academy Main App