#1424
Diagonal Traverse II
MediumArraySortingHeap (Priority Queue)Hash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution leverages a priority queue to efficiently group and sort the diagonal elements in one pass, reducing the need for multiple iterations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a priority queue to store tuples of (sum, row, value).
- 2Step 2: Iterate through the 2D array and for each element, calculate its diagonal index and push it into the priority queue.
- 3Step 3: Extract elements from the priority queue in order of their diagonal indices and append them to the result list.
solution.py12 lines
1import heapq
2
3def findDiagonalOrder(nums):
4 pq = []
5 for r in range(len(nums)):
6 for c in range(len(nums[r])):
7 heapq.heappush(pq, (r + c, r, nums[r][c]))
8 result = []
9 while pq:
10 _, r, val = heapq.heappop(pq)
11 result.append(val)
12 return resultℹ
Complexity note: The time complexity is O(n log n) due to the sorting of the priority queue, where n is the total number of elements. The space complexity remains O(n) for storing the elements.
- 1Elements on the same diagonal share the same sum of their row and column indices.
- 2Using a priority queue helps in efficiently sorting elements based on their diagonal indices.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.