This problem looks busy at first, but the accepted solution is built around one steady invariant. For 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows, the solution in this repository is mainly a heap / priority queue solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: heap / priority queue, greedy.
The notes already sitting in the source point us in the right direction:
- heap
- https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/discuss/609678/Python-O(k-*-logk-*-len(mat))-with-detailed-explanations-%2B-4-lines-python.
- time: O(k*logk*(m-1)), in which O(k*logk) is a iteration of heap operation
- space: O(k) = O(200)
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are kSmallestPairs, kthSmallest.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- The queue gives the solution a level-by-level or frontier-style traversal.
- The heap keeps the best candidate available without sorting the whole world every time.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
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(k*logk*(m-1)), in which O(k*logk) is a iteration of heap operation
- Space: O(k) = O(200)
Guide
C++ Solution
Your submission
The accepted solution
01//heap
02//https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/discuss/609678/Python-O(k-*-logk-*-len(mat))-with-detailed-explanations-%2B-4-lines-python.
03//Runtime: 280 ms, faster than 71.28% of C++ online submissions for Find the Kth Smallest Sum of a Matrix With Sorted Rows.
04//Memory Usage: 22.8 MB, less than 100.00% of C++ online submissions for Find the Kth Smallest Sum of a Matrix With Sorted Rows.
05//time: O(k*logk*(m-1)), in which O(k*logk) is a iteration of heap operation
06//space: O(k) = O(200)
07class Solution {
08public:
09 vector<int> kSmallestPairs(vector<int>& v1, vector<int>& v2, int k) {
10 auto comp = [&v1, &v2](vector<int>& p1, vector<int>& p2){
11 return v1[p1[0]] + v2[p1[1]] > v1[p2[0]] + v2[p2[1]];
12 };
13 priority_queue<vector<int>, vector<vector<int>>, decltype(comp)> pq(comp);
14
15 for(int i = 0; i < min((int)v1.size(), k); i++){
16 pq.push({i, 0});
17 }
18
19 vector<int> res;
20 vector<int> p;
21
22 while(k-- && !pq.empty()){
23 p = pq.top(); pq.pop();
24 res.push_back(v1[p[0]] + v2[p[1]]);
25 if(p[1]+1 < v2.size()) pq.push({p[0], p[1]+1});
26 }
27
28 return res;
29 };
30
31 int kthSmallest(vector<vector<int>>& mat, int k) {
32 int m = mat.size(), n = mat[0].size();
33
34 vector<int> res = mat[0];
35 //merge two rows m-1 times
36 for(int i = 1; i < m; i++){
37 res = kSmallestPairs(res, mat[i], k);
38 }
39
40 return res.back();
41 }
42};
43
44//https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/discuss/609678/Python-O(k-*-logk-*-len(mat))-with-detailed-explanations-%2B-4-lines-python.
45//Runtime: 552 ms, faster than 51.37% of C++ online submissions for Find the Kth Smallest Sum of a Matrix With Sorted Rows.
46//Memory Usage: 10.3 MB, less than 100.00% of C++ online submissions for Find the Kth Smallest Sum of a Matrix With Sorted Rows.
47class Solution {
48public:
49 int kthSmallest(vector<vector<int>>& mat, int k) {
50 vector<int> res = mat[0];
51 vector<int> tmp;
52
53 for(int i = 1; i < mat.size(); i++){
54 tmp.clear();
55 for(int a : res){
56 for(int b : mat[i]){
57 tmp.push_back(a+b);
58 }
59 }
60 sort(tmp.begin(), tmp.end());
61 res = vector<int>(tmp.begin(), tmp.begin()+min((int)tmp.size(), k));
62 }
63 // cout << res.size() << endl;
64 return res.back();
65 }
66};
Cost