Count the Number of K-Big Indices Problem
#2519
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2519.
You are given a 0-indexed integer array nums and a positive integer k.
We call an index i k-big if the following conditions are satisfied:
- There exist at least
kdifferent indicesidx1such thatidx1 < iandnums[idx1] < nums[i]. - There exist at least
kdifferent indicesidx2such thatidx2 > iandnums[idx2] < nums[i].
Return the number of k-big indices.
Example 1:
Input: nums = [2,3,6,5,2,3], k = 2
Output: 2
Explanation: 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:
Input: nums = [1,1,1], k = 3
Output: 0
Explanation: There are no 3-big indices in nums.
Constraints:
1 <= nums.length <= 10^51 <= nums[i], k <= nums.length
Solution
Approach: Two Binary Indexed Trees
An index i is k-big if at least k smaller values appear before it and at least k smaller values appear after it. Since values are at most n, we can count with Fenwick trees (binary indexed trees).
Keep tree1 with the values to the left of i (initially empty) and tree2 with the values to the right (initially everything). For each element, remove it from tree2, check that tree1 and tree2 each have at least k values smaller than it, then add it to tree1.
Complexity: O(n log n) time and O(n) space.
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
def update(self, x, delta):
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x):
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def kBigIndices(self, nums: List[int], k: int) -> int:
n = len(nums)
tree1 = BinaryIndexedTree(n)
tree2 = BinaryIndexedTree(n)
for v in nums:
tree2.update(v, 1)
ans = 0
for v in nums:
tree2.update(v, -1)
ans += tree1.query(v - 1) >= k and tree2.query(v - 1) >= k
tree1.update(v, 1)
return ans