Skip to content
prdlk
Esc
↑↓navigate↵open⌘Jpreview
On this page

54. Spiral Matrix

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

CompanyAsked withinFrequency
Bloomberg30 days70
Microsoft30 days57
Google30 days37
Amazon3 months46
Meta3 months35
Capital One6 months74
tcs6 months70
Apple6 months65
Infosys6 months56
TikTok6 months55

Example 1:

  • Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
  • Output: [1,2,3,6,9,8,7,4,5]

Example 2:

  • Input: matrix = [[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]

Constraints:

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

Approach

Solution

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        top, bottom = 0, len(matrix) - 1
        left, right = 0, len(matrix[0]) - 1

        while top <= bottom and left <= right:
            # 1. Top Row
            for c in range(left, right + 1):
                res.append(matrix[top][c])
            top += 1

            # 2. Right Column
            for r in range(top, bottom + 1):
                res.append(matrix[r][right])
            right -= 1

            # 3. Bottom Row
            if top <= bottom:
                for c in range(right, left - 1, -1):
                    res.append(matrix[bottom][c])
                bottom -= 1

            # 4. Left Column
            if left <= right:
                for r in range(bottom, top - 1, -1):
                    res.append(matrix[r][left])
                left += 1

        return res

Last updated on

Was this page helpful?