Skip to content

Commit 670faf3

Browse files
committed
3759
1 parent bedaaa1 commit 670faf3

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

explanations/3759/en.md

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,6 @@ We sort the array first, which allows us to efficiently determine how many eleme
2929
5. If the number of greater elements is at least `k`, add the count of current value to the result.
3030
6. Move to the next distinct value and repeat.
3131

32-
* **Brute Force:** For each element, count how many other elements are strictly greater by comparing with all other elements. This takes O(n^2) time.
33-
* **Optimized Strategy:** Sort the array first. Then for each distinct value, use binary search to find the first element strictly greater than it. The number of greater elements is `n - upper_bound_index`. This reduces the time complexity to O(n log n).
34-
3532
**2.1 Initialization & Example Setup:**
3633

3734
Let's use the example `nums = [3, 1, 2]`, `k = 1` to trace through the solution.

solutions/3759/01.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def countElements(self, nums: List[int], k: int) -> int:
6+
# Sort the array
7+
sorted_nums = sorted(nums)
8+
n = len(sorted_nums)
9+
10+
res = 0
11+
12+
# For each distinct value, count how many elements are strictly greater
13+
i = 0
14+
while i < n:
15+
# Count occurrences of current value
16+
count = 1
17+
while i + count < n and sorted_nums[i] == sorted_nums[i + count]:
18+
count += 1
19+
20+
# Find the first index with value strictly greater than current
21+
# Use binary search to find upper bound
22+
left, right = i + count, n
23+
while left < right:
24+
mid = (left + right) // 2
25+
if sorted_nums[mid] > sorted_nums[i]:
26+
right = mid
27+
else:
28+
left = mid + 1
29+
30+
# Number of elements strictly greater
31+
greater_count = n - left
32+
33+
# If at least k elements are greater, add count to result
34+
if greater_count >= k:
35+
res += count
36+
37+
i += count
38+
39+
return res

0 commit comments

Comments
 (0)