54. Spiral Matrix
Asked at 42Apple68Microsoft67Amazon64Bloomberg60Google59Meta53Epic Systems91TikTok73tcs69Infosys50RBC100Wissen Technology100Zoho99PornHub87eBay86Capital One82AMD79The Trade Desk69josh technology69NetApp68Cisco68Uber66Morgan Stanley64Akamai64Oracle64Adobe63Deutsche Bank62Paytm61Visa61Yahoo61Walmart Labs60Anduril60Nutanix60Autodesk59PhonePe53Flipkart52PayPal51Nvidia48IBM44Roblox37Goldman Sachs36Salesforce28
Problem
Return all elements of the m×n matrix in clockwise spiral order, starting at the top-left.
Example: [[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5]
Walk right along top, down along right, left along bottom, up along left, shrinking each boundary after use. Guard the last two walks for single rows/columns.
1 → 2 → 3 → 4
↓
5 → 6 → 7 8 order: 1 2 3 4 8 12 11 10 9 5 6 7
↑ ↓
9 ← 10 ← 11 ← 12
Complexity: O(m·n).
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
res += [matrix[top][c] for c in range(left, right + 1)]
res += [matrix[r][right] for r in range(top + 1, bottom + 1)]
if top < bottom and left < right:
res += [matrix[bottom][c] for c in range(right - 1, left - 1, -1)]
res += [matrix[r][left] for r in range(bottom - 1, top, -1)]
top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1
return res
assert Solution().spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [1, 2, 3, 6, 9, 8, 7, 4, 5]
assert Solution().spiralOrder([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) == [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) res.add(matrix[top][c]);
for (int r = top + 1; r <= bottom; r++) res.add(matrix[r][right]);
if (top < bottom && left < right) {
for (int c = right - 1; c >= left; c--) res.add(matrix[bottom][c]);
for (int r = bottom - 1; r > top; r--) res.add(matrix[r][left]);
}
top++; bottom--; left++; right--;
}
return res;
}
}
func spiralOrder(matrix [][]int) []int {
res := []int{}
top, bottom, left, right := 0, len(matrix)-1, 0, len(matrix[0])-1
for top <= bottom && left <= right { // peel one ring per round
for c := left; c <= right; c++ {
res = append(res, matrix[top][c])
}
for r := top + 1; r <= bottom; r++ {
res = append(res, matrix[r][right])
}
if top < bottom && left < right { // a single row or column has no way back
for c := right - 1; c >= left; c-- {
res = append(res, matrix[bottom][c])
}
for r := bottom - 1; r > top; r-- {
res = append(res, matrix[r][left])
}
}
top, bottom, left, right = top+1, bottom-1, left+1, right-1
}
return res
}