Diagonal Traverse II

medium heap priority queue matrix sorting

Problem

Given a (possibly jagged) 2D integer array nums, return all of its elements in diagonal order. Cells on the same anti-diagonal share the same value of i + j; smaller diagonals come first, and within a diagonal cells are listed from the bottom-left up to the top-right (decreasing row index order in the output reads bottom row first).

Inputnums = [[1,2,3],[4,5],[6]]
Output[1,4,2,6,5,3]
Diagonal 0: [1]; diagonal 1: [4,2]; diagonal 2: [6,5,3]. Within each diagonal the lower rows come first.
Inputnums = [[1,2,3],[4,5,6],[7,8,9]]
Output[1,4,2,7,5,3,8,6,9]
A full 3×3 grid traversed by anti-diagonals.

def findDiagonalOrder(nums):
    import heapq
    heap = []
    for i in range(len(nums)):
        for j in range(len(nums[i])):
            heapq.heappush(heap, (i + j, -i, nums[i][j]))
    res = []
    while heap:
        diag, neg_i, val = heapq.heappop(heap)
        res.append(val)
    return res
function findDiagonalOrder(nums) {
  const heap = [];                 // [diag, -i, val] tuples
  for (let i = 0; i < nums.length; i++)
    for (let j = 0; j < nums[i].length; j++)
      heap.push([i + j, -i, nums[i][j]]);
  heap.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  const res = [];
  for (const t of heap)
    res.push(t[2]);
  return res;
}
int[] findDiagonalOrder(List<List<Integer>> nums) {
    PriorityQueue<int[]> heap = new PriorityQueue<>(
        (a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);
    int total = 0;
    for (int i = 0; i < nums.size(); i++)
        for (int j = 0; j < nums.get(i).size(); j++) {
            heap.offer(new int[]{i + j, -i, nums.get(i).get(j)});
            total++;
        }
    int[] res = new int[total];
    for (int k = 0; k < total; k++)
        res[k] = heap.poll()[2];
    return res;
}
vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
    priority_queue<array<int,3>, vector<array<int,3>>,
                   greater<>> heap;
    for (int i = 0; i < (int)nums.size(); i++)
        for (int j = 0; j < (int)nums[i].size(); j++)
            heap.push({i + j, -i, nums[i][j]});
    vector<int> res;
    while (!heap.empty()) {
        res.push_back(heap.top()[2]);
        heap.pop();
    }
    return res;
}
Time: O(N log N) Space: O(N)