Problem
Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Using hashmap
Here is the approach:
- Using a HashMap to Group Elements by Diagonals:
- Traverse the matrix and use a hashmap to collect elements that belong to the same diagonal.
- The key for each diagonal in the hashmap is the sum of the row and column indices.
- Extract Elements from the HashMap:
- Read the diagonals from the hashmap in increasing order of their keys and collect elements.
Code
| |
| |
Complexity
- Time:
O(m * n), wheremis the number of rows andnis the number of columns. This is because we visit each element exactly once. - Space:
O(m * n), for storing the elements in the hashmap and the result list.