MediumNo. 1424
Diagonal Traverse II — LeetCode 1424 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Array, Sorting, Heap (Priority Queue)
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.
Example
- Input
- nums = [[1,2,3],[4,5,6],[7,8,9]]
- Output
- [1,4,2,7,5,3,8,6,9]
Python solution
class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
arr = []
for i, row in enumerate(nums):
for j, v in enumerate(row):
arr.append((i + j, j, v))
arr.sort()
return [v[2] for v in arr]Complexity
- Time
- O(n × log n)where n is the number of elements in the array nums
- Space · auxiliary
- O(n)
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1424. Diagonal Traverse II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0498 | Diagonal Traverse | Medium |
| 0215 | Kth Largest Element in an Array | Medium |
| 0218 | The Skyline Problem | Hard |
| 0506 | Relative Ranks | Easy |
| 0912 | Sort an Array | Medium |
| 0973 | K Closest Points to Origin | Medium |
Frequently asked questions
- How hard is LeetCode 1424. Diagonal Traverse II?
LeetCode 1424. Diagonal Traverse II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1424. Diagonal Traverse II?
The Python solution on this page runs in O(n × log n), where n is the number of elements in the array \textit{nums}.
- What is the space complexity of LeetCode 1424. Diagonal Traverse II?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1424. Diagonal Traverse II cover?
LeetCode 1424. Diagonal Traverse II is tagged Array, Sorting and Heap (Priority Queue) on LeetCode.