1424. Diagonal Traverse II LeetCode Solution
In this guide, you will get 1424. Diagonal Traverse II LeetCode Solution with the best time and space complexity. The solution to Diagonal Traverse II problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Diagonal Traverse II solution in C++
- Diagonal Traverse II solution in Java
- Diagonal Traverse II solution in Python
- Additional Resources
Problem Statement of Diagonal Traverse II
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
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
1424. Diagonal Traverse II LeetCode Solution in C++
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
vector<int> ans;
unordered_map<int, vector<int>> keyToNums; // key := row + column
int maxKey = 0;
for (int i = 0; i < nums.size(); ++i)
for (int j = 0; j < nums[i].size(); ++j) {
const int key = i + j;
keyToNums[key].push_back(nums[i][j]);
maxKey = max(maxKey, key);
}
for (int i = 0; i <= maxKey; ++i)
for (auto it = keyToNums[i].rbegin(); it != keyToNums[i].rend(); ++it)
ans.push_back(*it);
return ans;
}
};
/* code provided by PROGIEZ */
1424. Diagonal Traverse II LeetCode Solution in Java
class Solution {
public int[] findDiagonalOrder(List<List<Integer>> nums) {
List<Integer> ans = new ArrayList<>();
Map<Integer, List<Integer>> keyToNums = new HashMap<>(); // key := row + column
int maxKey = 0;
for (int i = 0; i < nums.size(); ++i)
for (int j = 0; j < nums.get(i).size(); ++j) {
final int key = i + j;
keyToNums.putIfAbsent(key, new ArrayList<>());
keyToNums.get(key).add(nums.get(i).get(j));
maxKey = Math.max(key, maxKey);
}
for (int i = 0; i <= maxKey; ++i)
for (int j = keyToNums.get(i).size() - 1; j >= 0; --j)
ans.add(keyToNums.get(i).get(j));
return ans.stream().mapToInt(Integer::intValue).toArray();
}
}
// code provided by PROGIEZ
1424. Diagonal Traverse II LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.