- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- 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.
Use this to learn the idea, then write your own version.
123 4import heapq5 6 7class Solution(object):8 def kthSmallest(self, mat, k):9 """10 :type mat: List[List[int]]11 :type k: int12 :rtype: int13 """14 def kSmallestPairs(nums1, nums2, k):15 result, min_heap = [], []16 for c in xrange(min(len(nums1), k)):17 heapq.heappush(min_heap, (nums1[c]+nums2[0], 0))18 c += 119 while len(result) != k and min_heap:20 total, c = heapq.heappop(min_heap)21 result.append(total)22 if c+1 == len(nums2):23 continue24 heapq.heappush(min_heap, (total-nums2[c]+nums2[c+1], c+1))25 return result26 27 result = mat[0]28 for r in xrange(1, len(mat)):29 result = kSmallestPairs(result, mat[r], k)30 return result[k-1]31 32 333435class Solution2(object):36 def kthSmallest(self, mat, k):37 """38 :type mat: List[List[int]]39 :type k: int40 :rtype: int41 """ 42 def countArraysHaveSumLessOrEqual(mat, k, r, target): 43 if target < 0:44 return 045 if r == len(mat):46 return 147 result = 048 for c in xrange(len(mat[0])):49 cnt = countArraysHaveSumLessOrEqual(mat, k-result, r+1, target-mat[r][c])50 if not cnt:51 break52 result += cnt53 if result > k:54 break55 return result56 57 max_num = max(x for row in mat for x in row)58 left, right = len(mat), len(mat)*max_num59 while left <= right:60 mid = left + (right-left)261 cnt = countArraysHaveSumLessOrEqual(mat, k, 0, mid)62 if cnt >= k:63 right = mid-164 else:65 left = mid+166 return left67 68