Diagonal Traverse II — LeetCode 1424 Python Solution
MediumArraySortingHeap (Priority Queue)
- Problem
- #1424
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n), where n is the number of elements in the array \textit{nums} |
| Space | O(n) auxiliary |
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
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 \times \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.