- 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
- 61 lines of Python from the credited upstream file count-elements-with-at-least-k-greater-values.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 78class Solution(object):9 def countElements(self, nums, k):10 """11 :type nums: List[int]12 :type k: int13 :rtype: int14 """15 def nth_element(nums, n, compare=lambda a, b: a < b):16 def tri_partition(nums, left, right, target, compare):17 mid = left18 while mid <= right:19 if nums[mid] == target:20 mid += 121 elif compare(nums[mid], target):22 nums[left], nums[mid] = nums[mid], nums[left]23 left += 124 mid += 125 else:26 nums[mid], nums[right] = nums[right], nums[mid]27 right -= 128 return left, right29 30 left, right = 0, len(nums)-131 while left <= right:32 pivot_idx = random.randint(left, right)33 pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)34 if pivot_left <= n <= pivot_right:35 return36 elif pivot_left > n:37 right = pivot_left-138 else: 39 left = pivot_right+140 41 if not k:42 return len(nums)43 nth_element(nums, len(nums)-k)44 return sum(nums[i] < nums[-k] for i in xrange(len(nums)-k))45 46 47484950class Solution2(object):51 def countElements(self, nums, k):52 """53 :type nums: List[int]54 :type k: int55 :rtype: int56 """57 if not k:58 return len(nums)59 nums.sort()60 return next((i for i in reversed(xrange(len(nums)-k)) if nums[i] < nums[-k]), -1)+161