Count Elements Having At Least K Greater Elements
You are given an integer array nums of size n and an integer k.
An element nums[i] is called valid if there are at least k elements in the array whose values are strictly greater than nums[i].
Return the total number of valid elements in the array.
Notes:
- Each array position is treated independently.
- Only elements with a strictly greater value are counted.
- Equal values are not considered greater.
Example 1:
Input: nums = [4, 1, 3, 2], k = 2
Output: 2
Explanation:
- For 1, the greater elements are 4 and 3 and 2 → count = 3
- For 2, the greater elements are 4 and 3 → count = 2
- For 3, only 4 is greater → count = 1
- For 4, no element is greater → count = 0
So, the valid elements are 1 and 2. Hence, the answer is 2.
Example 2:
Input: nums = [7, 7, 5, 4], k = 1
Output: 2
Explanation:
- For the first 7, no element is greater
- For the second 7, no element is greater
- For 5, there are two greater elements: 7 and 7
- For 4, there are three greater elements: 7, 7, and 5
So, the valid elements are 5 and 4. Hence, the answer is 2.
Now Your Turn!
Pick the correct output for the given inputInput: nums = [6, 2, 6, 1], k = 2
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 109
- 0 <= k < nums.length