Talentd
FleetCode

1424. Diagonal Traverse II

Medium58.3% acceptance5 companies

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

Asked at 5 companies

Hints open one at a time

Hint 1
Notice that numbers with equal sums of row and column indexes belong to the same diagonal.
Hint 2
Store them in tuples (sum, row, val), sort them, and then regroup the answer.
31:46
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
3
Starter codePython 3Spaces: 4
Examples
Input
[[1,2,3],[4,5,6],[7,8,9]]
Input
[[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
Your code is saved on this device.Solution