Problem solution · Python

Find the Kth Smallest Sum of a Matrix with Sorted Rows

Find the Kth Smallest Sum of a Matrix with Sorted Rows: a Python solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Sliding window or two pointers
Source
Kamyu LeetCode Solutions
Length
68 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

Sliding window or two pointers

For Find the Kth Smallest Sum of a Matrix with Sorted Rows, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 68 lines of Python from the credited upstream file find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows.py.
  • The implementation visibly relies on sequence storage, work queue.
  • No explicit loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

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

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeFind the Kth Smallest Sum of a Matrix with Sorted Rows · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(m * klogk)# Space: O(k) import heapq  class Solution(object):    def kthSmallest(self, mat, k):        """        :type mat: List[List[int]]        :type k: int        :rtype: int        """        def kSmallestPairs(nums1, nums2, k):            result, min_heap = [], []            for c in xrange(min(len(nums1), k)):                heapq.heappush(min_heap, (nums1[c]+nums2[0], 0))                c += 1            while len(result) != k and min_heap:                total, c = heapq.heappop(min_heap)                result.append(total)                if c+1 == len(nums2):                    continue                heapq.heappush(min_heap, (total-nums2[c]+nums2[c+1], c+1))            return result         result = mat[0]        for r in xrange(1, len(mat)):            result = kSmallestPairs(result, mat[r], k)        return result[k-1]  # Time:  O((k + m) * log(m * MAX_NUM)) ~ O(k * m * log(m * MAX_NUM))# Space: O(m)class Solution2(object):    def kthSmallest(self, mat, k):        """        :type mat: List[List[int]]        :type k: int        :rtype: int        """                def countArraysHaveSumLessOrEqual(mat, k, r, target):  # Time: O(k + m) ~ O(k * m)            if target < 0:                return 0            if r == len(mat):                return 1            result = 0            for c in xrange(len(mat[0])):                cnt = countArraysHaveSumLessOrEqual(mat, k-result, r+1, target-mat[r][c])                if not cnt:                    break                result += cnt                if result > k:                    break            return result                max_num = max(x for row in mat for x in row)        left, right = len(mat), len(mat)*max_num        while left <= right:            mid = left + (right-left)//2            cnt = countArraysHaveSumLessOrEqual(mat, k, 0, mid)            if cnt >= k:                right = mid-1            else:                left = mid+1        return left  

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 ↗