Given an m x n matrix, return all elements of the matrix in spiral order.
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.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are tasked with collecting every single item from a grid by walking around its outer edges and gradually moving inward. The brute force approach exhaustively traces the entire path by systematically visiting every location on the grid one by one, following a strict set of directional rules until no unvisited locations remain.
Here's how the algorithm would work step-by-step:
def spiralOrder(matrix):
if not matrix:
return []
row_count = len(matrix)
column_count = len(matrix[0])
total_elements = row_count * column_count
visited_matrix = [[False for _ in range(column_count)] for _ in range(row_count)]
result_collection = []
row_index = 0
column_index = 0
current_direction = 0
row_directions = [0, 1, 0, -1]
column_directions = [1, 0, -1, 0]
# Traverse step-by-step, turning clockwise only when hitting boundaries or visited cells
for step_counter in range(total_elements):
result_collection.append(matrix[row_index][column_index])
visited_matrix[row_index][column_index] = True
next_row = row_index + row_directions[current_direction]
next_column = column_index + column_directions[current_direction]
if (0 <= next_row < row_count) and (0 <= next_column < column_count) and not visited_matrix[next_row][next_column]:
row_index = next_row
column_index = next_column
else:
current_direction = (current_direction + 1) % 4
row_index += row_directions[current_direction]
column_index += column_directions[current_direction]
# Return the fully collected spiral sequence once all grid locations are processed
return result_collectionThe optimal approach to solving this puzzle is to peel away the grid like the layers of an onion, moving strictly along the outer edges in a continuous clockwise loop. By shrinking the active boundaries inward after completing each full circuit, we visit every single spot exactly once without missing a corner or overlapping.
Here's how the algorithm would work step-by-step:
def spiral_order(matrix_grid):
if not matrix_grid:
return []
result_collection = []
top_boundary = 0
bottom_boundary = len(matrix_grid) - 1
left_boundary = 0
right_boundary = len(matrix_grid[0]) - 1
# We peel the matrix layer by layer until boundaries cross, ensuring all elements are visited.
while top_boundary <= bottom_boundary and left_boundary <= right_boundary:
for column_index in range(left_boundary, right_boundary + 1):
result_collection.append(matrix_grid[top_boundary][column_index])
top_boundary += 1
for row_index in range(top_boundary, bottom_boundary + 1):
result_collection.append(matrix_grid[row_index][right_boundary])
right_boundary -= 1
# Checking boundaries prevents duplicate processing of rows or columns in non-square matrices.
if top_boundary <= bottom_boundary:
for column_index in range(right_boundary, left_boundary - 1, -1):
result_collection.append(matrix_grid[bottom_boundary][column_index])
bottom_boundary -= 1
# Checking boundaries prevents duplicate processing of rows or columns in non-square matrices.
if left_boundary <= right_boundary:
for row_index in range(bottom_boundary, top_boundary - 1, -1):
result_collection.append(matrix_grid[row_index][left_boundary])
left_boundary += 1
return result_collection| Case | How to Handle |
|---|---|
| Empty matrix or null input where rows or columns equal zero | Check for empty input upfront and return an empty list immediately to prevent out-of-bounds errors. |
| Single row matrix of dimensions 1 x n | The outer loop runs once, and the right-to-left and bottom-to-top traversal steps are skipped by boundary checks. |
| Single column matrix of dimensions m x 1 | The traversal correctly processes the single column downwards while horizontal loops are safely bypassed. |
| A 1 x 1 matrix containing just a single element | The algorithm appends the single element and terminates without triggering any out-of-bounds boundary violations. |
| Extremely large matrices near memory limits | The O(m * n) time and O(1) auxiliary space approach prevents memory overflow by avoiding recursion. |
| Matrices containing negative numbers, zeros, and extreme boundary values | Since the algorithm only reads values and checks coordinate bounds, value magnitudes do not affect traversal. |
| Non-square rectangular matrices where rows and columns differ significantly | Using four distinct boundary pointers ensures correct inward shrinkage regardless of aspect ratio. |
| Boundary cross-over during the final inner layer traversal | Strict conditional checks inside the loops prevent duplicate element insertions when rows or columns collapse. |