Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,4,7,5,3,6,8,9]
Example 2:
Input: mat = [[1,2],[3,4]] Output: [1,2,3,4]
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n <= 1041 <= m * n <= 104-105 <= mat[i][j] <= 105When 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 looking at a grid of items where you need to collect every single item by walking back and forth along slanted paths. The brute force approach involves painstakingly mapping out and following every single possible slanted path from start to finish, one direction at a time.
Here's how the algorithm would work step-by-step:
def find_diagonal_order(matrix):
if not matrix or not matrix[0]:
return []
row_count = len(matrix)
col_count = len(matrix[0])
collected_items = []
# We map out every starting point along the top row and rightmost column to cover all diagonals
for start_index in range(row_count + col_count - 1):
diagonal_bucket = []
if start_index < col_count:
row_index = 0
col_index = start_index
else:
row_index = start_index - col_count + 1
col_index = col_count - 1
while row_index < row_count and col_index >= 0:
diagonal_bucket.append(matrix[row_index][col_index])
row_index += 1
col_index -= 1
# Alternating directions is necessary because consecutive diagonals must be traversed in opposite ways
if start_index % 2 == 0:
diagonal_bucket.reverse()
collected_items.extend(diagonal_bucket)
return collected_itemsImagine walking along a grid of numbers by bouncing diagonally back and forth like a billiard ball hitting the walls. Instead of jumping around randomly, we can trace a continuous path by carefully managing our direction and knowing when to turn around at the boundaries.
Here's how the algorithm would work step-by-step:
def find_diagonal_order(matrix):
if not matrix or not matrix[0]:
return []
row_count = len(matrix)
col_count = len(matrix[0])
result_list = []
row_index = 0
col_index = 0
going_up = True
while len(result_list) < row_count * col_count:
result_list.append(matrix[row_index][col_index])
# We change direction and shift position when hitting boundaries while moving up.
if going_up:
if col_index == col_count - 1:
row_index += 1
going_up = False
elif row_index == 0:
col_index += 1
going_up = False
else:
row_index -= 1
col_index += 1
# We adjust coordinates and reverse direction when reaching boundaries while moving down.
else:
if row_index == row_count - 1:
col_index += 1
going_up = True
elif col_index == 0:
row_index += 1
going_up = True
else:
row_index += 1
col_index -= 1
# The collected traversal path is returned once every matrix element has been visited.
return result_list| Case | How to Handle |
|---|---|
| Empty matrix with zero rows or zero columns | Check for null or empty input dimensions at the start and return an empty array immediately. |
| Single row matrix with multiple columns | The traversal logic should successfully process the single horizontal line without out-of-bounds errors. |
| Single column matrix with multiple rows | The direction-switching mechanism must handle vertical movement correctly without skipping rows. |
| Single element matrix | The algorithm should immediately capture the single value and return a one-element array. |
| Matrix dimensions are extremely large | Iterative simulation with O(m times n) time and O(min(m, n)) space complexity prevents stack overflow or excessive memory usage. |
| Matrix containing negative numbers, zeros, and extreme boundary values | Value types do not affect traversal indices, so standard integer data handling applies natively. |
| Reaching the top-most or right-most boundary during upward-right movement | Conditional checks prioritize row or column increments to correctly pivot the direction downwards-left. |
| Reaching the bottom-most or left-most boundary during downward-left movement | Boundary collision rules correctly adjust indices to shift movement back upwards-right. |