Problem solution · C++

Find the Kth Smallest Sum of a Matrix With Sorted Rows

Find the Kth Smallest Sum of a Matrix With Sorted Rows: a C++ solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Heap or priority queue
Source
walkccc LeetCode Solutions
Length
39 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Find the Kth Smallest Sum of a Matrix With Sorted Rows, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. Discard stale entries when necessary and process the best live candidate.

Code notes

  • 39 lines of C++ from the credited upstream file 1439.cpp.
  • The implementation visibly relies on sequence storage, work queue.
  • 3 loop blocks detected.

Complexity

Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFind the Kth Smallest Sum of a Matrix With Sorted Rows · C++C++
Use this to learn the idea, then write your own version.
struct T {  int i;  int j;  int sum;  // nums1[i] + nums2[j]}; class Solution { public:  int kthSmallest(vector<vector<int>>& mat, int k) {    vector<int> row = mat[0];     for (int i = 1; i < mat.size(); ++i)      row = kSmallestPairSums(row, mat[i], k);     return row.back();  }  private:  // Similar to 373. Find K Pairs with Smallest Sums  vector<int> kSmallestPairSums(vector<int>& nums1, vector<int>& nums2, int k) {    vector<int> ans;    auto compare = [&](const T& a, const T& b) { return a.sum > b.sum; };    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);     for (int i = 0; i < k && i < nums1.size(); ++i)      minHeap.emplace(i, 0, nums1[i] + nums2[0]);     while (!minHeap.empty() && ans.size() < k) {      const auto [i, j, _] = minHeap.top();      minHeap.pop();      ans.push_back(nums1[i] + nums2[j]);      if (j + 1 < nums2.size())        minHeap.emplace(i, j + 1, nums1[i] + nums2[j + 1]);    }     return ans;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗