Diagonal Traverse II

Medium · Matrix · Array · Matrix · Breadth-First Search

Problem

You are given a jagged 2D integer array nums: rows may have different lengths. Group the cells by anti-diagonal, the value of row + col, and visit the groups in increasing order of row + col.

Within one anti-diagonal, visit the cells from the bottom-most row upward (largest row index first). Return all elements in this order.

Examples

Input: nums = [[1,2,3],[4,5],[6]]
Output: [1,4,2,6,5,3]

Diagonal 0 is [1], diagonal 1 is 4 then 2, diagonal 2 is 6, 5, 3 from the bottom up.

Input: nums = [[1,2],[3],[4,5,6]]
Output: [1,3,2,4,5,6]

Diagonal 1 is 3 then 2. Diagonal 2 holds only 4, because rows 0 and 1 are too short; 5 and 6 each sit alone on later diagonals.

Input: nums = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,4,2,7,5,3,8,6,9]

A full square: 1, then 4 2, then 7 5 3, then 8 6, then 9.

Constraints

Approaches

Follow-up

Sorting the cells by (row + col, -row) also works, in O(N log N). The bucket and BFS solutions avoid the sort because the keys are small integers and the order inside a bucket comes for free.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…