Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1424: Diagonal Traverse II

In this guide, we solve Leetcode #1424 Diagonal Traverse II in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images. Example 1: Input: nums = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,4,2,7,5,3,8,6,9] Example 2: Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16] Constraints: 1 <= nums.length <= 105 1 <= nums[i].length <= 105 1 <= sum(nums[i].length) <= 105 1 <= nums[i][j] <= 105

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Sorting, Heap (Priority Queue)

Intuition

We need to repeatedly access the smallest or largest element as the input changes.

A heap provides fast insertions and removals while keeping order.

Approach

Push candidates into the heap as you scan, and pop when you need the best element.

Keep the heap size bounded if the problem requires a top-k structure.

Steps:

  • Push candidates into a heap.
  • Pop the best candidate when needed.
  • Maintain heap size or invariants.

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

The time complexity is O(n×log⁡n)O(n \times \log n)O(n×logn), where nnn is the number of elements in the array nums\textit{nums}nums. The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy