Taro Logo

Diagonal Traverse

#1 Most AskedMedium
0 views
Topics:
Arrays

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.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • -105 <= mat[i][j] <= 105

Solution


Clarifying Questions

When 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:

  1. What are the dimensions of the input matrix `mat`, and can the matrix be non-square (i.e., $m eq n$)?
  2. Can the matrix be empty (e.g., $0 imes 0$, or dimensions where $m=0$ or $n=0$), and if so, should we return an empty array?
  3. What data types are contained within the matrix elements (e.g., standard integers, floats), and should we expect negative numbers, zeros, or extreme values?
  4. Can the matrix consist of a single row or a single column (e.g., $1 imes n$ or $m imes 1$), and how should the zig-zag traversal behave in those cases?
  5. Is the return type expected to be a standard one-dimensional list or array of integers?

Brute Force Solution

Approach

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:

  1. Begin at the topmost starting point of the grid.
  2. Walk along the first slanted path upwards and write down every item you encounter.
  3. Move to the next starting point and walk along the next slanted path downwards, writing down those items as well.
  4. Keep repeating this process, alternating between walking upwards and downwards along every possible slanted path until you have visited every single starting point on the top and right edges.
  5. Gather all the items you collected from each slanted walk and put them together in the exact order you visited them.
  6. Review the final combined list of items to ensure nothing was missed and every single item from the grid is accounted for.

Code Implementation

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_items

Big(O) Analysis

Time Complexity
O(m * n) – To traverse the grid, we visit every single cell exactly once along the alternating slanted paths, where m is the number of rows and n is the number of columns. The cost is entirely driven by the total number of elements in the matrix since each cell is processed in constant time during our zig-zag walks. Summing up the work across all rows and columns gives us approximately m * n total operations. Because every cell is accounted for linearly, this simplifies to the final Big O notation of O(m * n).
Space Complexity
O(M * N) – To gather all the items you collected from each slanted walk and put them together in the exact order, the algorithm allocates a single output list. If we define N as the total number of elements in the grid (or M times N where M and N are the dimensions of the grid), this result container stores every single element. No additional data structures, hash maps, or recursion stacks are utilized during the back and forth traversal. Therefore, the extra memory required scales directly and linearly with the total element count of the grid.

Optimal Solution

Approach

Imagine 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:

  1. Begin your journey at the very top-left corner of the grid, facing upwards and to the right.
  2. As you move, keep track of whether you are traveling upwards or downwards.
  3. Whenever you are moving upwards and hit either the top ceiling or the right-hand wall, you need to bounce. If you hit the top, step one space to the right; if you hit the right wall, step one space down, and then switch your direction to go downwards.
  4. Whenever you are moving downwards and hit either the bottom floor or the left-hand wall, you also need to bounce. If you hit the left wall, step one space down; if you hit the bottom floor, step one space to the right, and then switch your direction to go upwards.
  5. Continue this process of stepping diagonally, hitting the boundaries, making the correct adjustment, and reversing direction until you reach the opposite corner at the bottom right.
  6. Collect every number you encounter along this zigzag path in the exact order you visit them to form your final single line of numbers.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(m * n) – To traverse the entire grid, we must visit every single one of the m rows and n columns exactly once. The total operations are driven by a single traversal loop that processes every element in the matrix sequentially. Across the entire grid, the total number of visited elements equals the product of the dimensions, which is m * n. Because each cell is visited in constant time, the total operations directly correspond to this product and simplify to O(m * n).
Space Complexity
O(M * N) – The algorithm collects every number encountered along the zigzag path to form a final single line of numbers. Specifically, we store the result in an auxiliary output array whose size matches the total number of elements in the grid, which we can denote as N. Therefore, the extra memory required scales linearly with the total element count of the input matrix. Aside from this output collection and a few primitive tracking variables, no additional data structures are used.

Edge Cases

Empty matrix with zero rows or zero columns
How to Handle:
Check for null or empty input dimensions at the start and return an empty array immediately.
Single row matrix with multiple columns
How to Handle:
The traversal logic should successfully process the single horizontal line without out-of-bounds errors.
Single column matrix with multiple rows
How to Handle:
The direction-switching mechanism must handle vertical movement correctly without skipping rows.
Single element matrix
How to Handle:
The algorithm should immediately capture the single value and return a one-element array.
Matrix dimensions are extremely large
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Boundary collision rules correctly adjust indices to shift movement back upwards-right.
0/4 completed