Count Elements With at Least K Greater Values Problem
Description
LeetCode Problem 3759.
You are given an integer array nums of length n and an integer k.
An element in nums is said to be qualified if there exist at least k elements in the array that are strictly greater than it.
Return an integer denoting the total number of qualified elements in nums.
Example 1:
Input: nums = [3,1,2], k = 1
Output: 2
Explanation:
The elements 1 and 2 each have at least k = 1 element greater than themselves.
No element is greater than 3. Therefore, the answer is 2.
Example 2:
Input: nums = [5,5,5], k = 2
Output: 0
Explanation:
Since all elements are equal to 5, no element is greater than the other. Therefore, the answer is 0.
Constraints:
1 <= n == nums.length <= 10^51 <= nums[i] <= 10^90 <= k < n
Solution
Approach: Sorting
If k = 0, every element has at least 0 larger elements, so the answer is n.
Otherwise sort the array. After sorting, the k largest elements sit at indices n - k to n - 1. Look at the value v = nums[n - k], the smallest of those k elements. An element at index i < n - k has at least k strictly larger elements exactly when nums[i] < v: if it is smaller than v, then v and everything after it are larger; if it equals v, only the k - 1 elements after v are guaranteed to be larger. Elements at index n - k or later are never qualified, because fewer than k elements come after them in sorted order.
So count the indices i < n - k with nums[i] < nums[n - k].
Complexity: O(n log n) time for the sort and O(1) extra space besides the sort.
class Solution:
def countElements(self, nums: List[int], k: int) -> int:
n = len(nums)
if k == 0:
return n
nums.sort()
return sum(nums[n - k] > nums[i] for i in range(n - k))