### Leetcode #1424: Diagonal Traverse II

Diagonal Traverse II

### Key Idea

In a 2D matrix, elements in the same diagonal have same sum of their indices.

So if we have all elements with same sum of their indices together, then it’s just a matter of printing those elements in order.

### Algorithm

1. Insert all elements into an appropriate bucket i.e. nums[i][j] in (i+j)th bucket.
2. For each bucket starting from 0 to max, print all elements in the bucket.
Note: Here, diagonals are from bottom to top, but we traversed the input matrix from first row to last row. Hence we need to print the elements in reverse order.

### Code

 vector findDiagonalOrder(vector>& nums) { vector answer; unordered_map> m; int maxKey = 0; // maximum key inserted into the map i.e. max value of i+j indices. for (int i=0; i
view raw Leetcode_1424.cpp hosted with ❤ by GitHub

Is there anything that is still unclear? Let me know in the comments and I can elaborate further.

Don’t forget to like & share the post, and subscribe to the blog to get notifications whenever solution to a new problem is added.

Happy Coding!