We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Diagonal Traverse II

Number: 1539

Difficulty: Medium

Paid? No

Companies: Meta, Google


Problem Description

Given a 2D integer array nums (which can be a jagged array), return all elements of nums in diagonal order. The elements should be traversed diagonally so that for each diagonal (defined by the sum of row and column indices), the order of traversal is from the bottom-most element in that diagonal to the top-most element.


Key Insights

  • The diagonal key for each element can be defined as (row_index + column_index).
  • Elements in the same diagonal (with equal diagonal key) must be output in an order such that the element from the lower row comes before the one from a higher row.
  • Because the input grid may be jagged (rows with varying lengths), you must carefully iterate only over valid indices.
  • A hash table (or map) can be used to collect elements grouped by their diagonal key.
  • Inserting each element at the beginning of the list for that diagonal builds the list in the desired order without needing an extra reverse step later.
  • Finally, traverse the keys in increasing order (from 0 to maximum key) to produce the final result.

Space and Time Complexity

Time Complexity: O(N), where N is the total number of elements (each element is processed once). Space Complexity: O(N), for storing the elements in the map and the output array.


Solution

The solution iterates over every element in nums while computing its diagonal key as (i + j). For each element, the value is inserted at the beginning of the list corresponding to that diagonal key. This ensures that when the diagonal groups are later concatenated in order of increasing key, the internal ordering within each diagonal is correct (i.e., elements appear from the bottom of the diagonal to the top). The final result is built by iterating over the keys in sorted order and appending each list of diagonal elements.


Code Solutions

def findDiagonalOrder(nums):
    # Use a dictionary to collect elements by their diagonal key (i + j)
    from collections import defaultdict
    diagonals = defaultdict(list)
    
    # Iterate over each row and its elements
    for i, row in enumerate(nums):
        for j, value in enumerate(row):
            # Insert at the beginning to achieve the desired order for the diagonal
            diagonals[i + j].insert(0, value)
    
    result = []
    # Process the diagonals in order of increasing key
    for key in sorted(diagonals.keys()):
        result.extend(diagonals[key])
    return result

# Example usage:
# nums = [[1,2,3],[4,5,6],[7,8,9]]
# print(findDiagonalOrder(nums))  # Output: [1,4,2,7,5,3,8,6,9]
← Back to All Questions