Input: nums =[2,3,6,5,2,3], k =2Output: 2Explanation: There are only two 2-big indices in nums:- i =2--> There are two valid idx1:0 and 1. There are three valid idx2:2,3, and 4.- i =3--> There are two valid idx1:0 and 1. There are two valid idx2:3 and 4.
Example 2:
1
2
3
Input: nums =[1,1,1], k =3Output: 0Explanation: There are no 3-big indices in nums.
We need to count, for each index, the number of elements less than nums[i] to its left and right. This is a classic use case for a Binary Indexed Tree (Fenwick Tree) or a Segment Tree, as we need to efficiently count and update frequencies.
classBIT:
def__init__(self, n):
self.n = n
self.tree = [0] * (n+2)
defupdate(self, i, v):
i +=1while i <= self.n+1:
self.tree[i] += v
i += i &-i
defquery(self, i):
i +=1 res =0while i >0:
res += self.tree[i]
i -= i &-i
return res
classSolution:
defkBigIndices(self, nums: list[int], k: int) -> int:
n = len(nums)
arr = sorted(set(nums))
idx = {v: i for i, v in enumerate(arr)}
nums2 = [idx[v] for v in nums]
left = [0]*n
bit = BIT(len(arr))
for i in range(n):
left[i] = bit.query(nums2[i]-1)
bit.update(nums2[i], 1)
right = [0]*n
bit = BIT(len(arr))
for i in range(n-1, -1, -1):
right[i] = bit.query(nums2[i]-1)
bit.update(nums2[i], 1)
ans =0for i in range(n):
if left[i] >= k and right[i] >= k:
ans +=1return ans
classSolution {
classBIT {
int[] tree;
int n;
BIT(int n) {
this.n= n;
tree =newint[n+2];
}
voidupdate(int i, int v) {
i++;
while (i <= n+1) {
tree[i]+= v;
i += i &-i;
}
}
intquery(int i) {
i++;
int res = 0;
while (i > 0) {
res += tree[i];
i -= i &-i;
}
return res;
}
}
publicintkBigIndices(int[] nums, int k) {
int n = nums.length;
int[] arr = java.util.Arrays.stream(nums).distinct().sorted().toArray();
java.util.Map<Integer, Integer> idx =new java.util.HashMap<>();
for (int i = 0; i < arr.length; ++i) idx.put(arr[i], i);
int[] nums2 =newint[n];
for (int i = 0; i < n; ++i) nums2[i]= idx.get(nums[i]);
int[] left =newint[n];
BIT bit =new BIT(arr.length);
for (int i = 0; i < n; ++i) {
left[i]= bit.query(nums2[i]-1);
bit.update(nums2[i], 1);
}
int[] right =newint[n];
bit =new BIT(arr.length);
for (int i = n-1; i >= 0; --i) {
right[i]= bit.query(nums2[i]-1);
bit.update(nums2[i], 1);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
if (left[i]>= k && right[i]>= k) ans++;
}
return ans;
}
}