MediumNo. 1424

Diagonal Traverse II — LeetCode 1424 Python Solution

Topics
Array, Sorting, Heap (Priority Queue)
Reading time
2 min

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

PythonSolution
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

Related problems
No.ProblemDifficulty
0498Diagonal TraverseMedium
0215Kth Largest Element in an ArrayMedium
0218The Skyline ProblemHard
0506Relative RanksEasy
0912Sort an ArrayMedium
0973K Closest Points to OriginMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.