← Home

1424. Diagonal Traverse II

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
142

Let's make this one less mysterious. For 1424. Diagonal Traverse II, the solution in this repository is mainly a greedy solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

The notes already sitting in the source point us in the right direction:

  • TLE
  • 53 / 56 test cases passed.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findDiagonalOrder, ns, diags.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02//53 / 56 test cases passed.
03class Solution {
04public:
05    vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
06        int m = nums.size(), n = 0, total = 0;
07        vector<int> ns(m, 0);
08        vector<long long> diags(m, 0);
09        
10        for(int i = 0; i < m; i++){
11            n = max((int)nums[i].size(), n);
12            ns[i] = (int)nums[i].size();
13            diags[i] = (long long)ns[i] + i;
14            total += ns[i];
15        }
16        
17        vector<int> ans(total, 0);
18        int cur = 0;
19        
20        // cout << "total: " << total << endl;
21        for(int diag = 0; diag <= m-1+n-1; diag++){
22//             for(int i = min(diag, m-1); i >= 0; i--){
23//                 // auto it = find_if(ns.begin(), ns.end(), [](int n){return n > diag - i;});
24//                 // while (it != std::end(myvec))
25                
26                
27//                 int j = diag - i;
28//                 // if(nums[i].size() > j){
29//                 if(ns[i] > j){
30//                     // ans.push_back(nums[i][j]);
31//                     ans[cur++] = nums[i][j];
32//                 }
33                
34//             }
35            
36            // cout << "cur: " << cur << endl;
37            if(cur == ans.size()) break;
38            vector<long long>::iterator it = diags.begin();
39            
40            while(it != diags.end()){
41                it = find_if(it, diags.end(), [&diag](long long x){
42                    return x > diag;
43                });
44
45                if(it == diags.end()) break;
46
47                // int i = (it - diags.begin());
48                int i = distance(begin(diags), it);
49                
50                // cout << i << " " << diag-i << endl;
51                
52                if(diag-i < 0) break;
53
54                ans[cur++] = nums[i][(int)(diag-i)];
55
56                it = next(it);
57                // it = diags.end();
58            }
59            
60        }
61        
62        return ans;
63    }
64};
65
66//sort
67//Runtime: 1436 ms, faster than 7.58% of C++ online submissions for Diagonal Traverse II.
68//Memory Usage: 99.4 MB, less than 100.00% of C++ online submissions for Diagonal Traverse II.
69class Solution {
70public:
71    vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
72        int m = nums.size();
73        if(m == 0) return vector<int>();
74        vector<vector<int>> tuples;
75        
76        for(int i = 0; i < m; i++){
77            for(int j = 0; j < nums[i].size(); j++){
78                /*
79                first sort by row index + col index, ascending,  
80                and then by row index, descending
81                */
82                tuples.push_back({i+j, -i, nums[i][j]});
83            }
84        }
85        
86        sort(tuples.begin(), tuples.end());
87        
88        vector<int> ans(tuples.size());
89        
90        for(int i = 0; i < ans.size(); i++){
91            ans[i] = tuples[i][2];
92        }
93        
94        return ans;
95    }
96};
97
98//bucket(hashmap)
99//https://leetcode.com/problems/diagonal-traverse-ii/discuss/597741/Clean-Simple-Easiest-Explanation-with-a-picture-and-code-with-comments
100//Runtime: 504 ms, faster than 86.78% of C++ online submissions for Diagonal Traverse II.
101//Memory Usage: 94.3 MB, less than 100.00% of C++ online submissions for Diagonal Traverse II.
102class Solution {
103public:
104    vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
105        unordered_map<int, vector<int>> bucket;
106        int maxKey = INT_MIN;
107        int count = 0;
108        
109        for(int i = 0; i < nums.size(); i++){
110            for(int j = 0; j < nums[i].size(); j++){
111                bucket[i+j].push_back(nums[i][j]);
112                maxKey = max(maxKey, i+j);
113                count++;
114            }
115        }
116        
117        vector<int> ans(count);
118        int idx = 0;
119        
120        for(int i = 0; i <= maxKey; i++){
121            for(int j = bucket[i].size()-1; j >= 0; j--){
122                ans[idx++] = bucket[i][j];
123            }
124        }
125        
126        return ans;
127    }
128};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.