- 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
- 53 lines of Python from the credited upstream file find-kth-largest-xor-coordinate-value.py.
- The implementation visibly relies on sequence storage.
- 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 random5 6 7class Solution(object):8 def kthLargestValue(self, matrix, k):9 """10 :type matrix: List[List[int]]11 :type k: int12 :rtype: int13 """14 def nth_element(nums, n, compare=lambda a, b: a < b):15 def tri_partition(nums, left, right, target, compare):16 mid = left17 while mid <= right:18 if nums[mid] == target:19 mid += 120 elif compare(nums[mid], target):21 nums[left], nums[mid] = nums[mid], nums[left]22 left += 123 mid += 124 else:25 nums[mid], nums[right] = nums[right], nums[mid]26 right -= 127 return left, right28 29 left, right = 0, len(nums)-130 while left <= right:31 pivot_idx = random.randint(left, right)32 pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)33 if pivot_left <= n <= pivot_right:34 return35 elif pivot_left > n:36 right = pivot_left-137 else: 38 left = pivot_right+139 40 41 vals = []42 for r in xrange(len(matrix)):43 curr = 044 for c in xrange(len(matrix[0])):45 curr = curr^matrix[r][c]46 if r == 0:47 matrix[r][c] = curr48 else:49 matrix[r][c] = curr^matrix[r-1][c]50 vals.append(matrix[r][c])51 nth_element(vals, k-1, compare=lambda a, b: a > b)52 return vals[k-1]53