Problem Description
Given a 0-indexed integer array nums and a positive integer k, an index i is defined as k-big if:
- There exist at least k indices j (with j < i) such that nums[j] < nums[i].
- There exist at least k indices j (with j > i) such that nums[j] < nums[i]. Return the number of k-big indices in the array.
Key Insights
- To determine the count of elements less than the current element on the left and right, a data structure that supports fast prefix queries is needed.
- A Fenwick Tree (also known as Binary Indexed Tree) or Segment Tree can efficiently maintain prefix counts during iteration.
- First, perform coordinate compression to handle a potentially wide range of numbers and map them to a smaller range.
- Compute two arrays: one for left counts (by scanning from left to right) and one for right counts (by scanning from right to left).
- An index i qualifies as k-big if both counts are at least k.
Space and Time Complexity
Time Complexity: O(n log n) where n is the length of nums (due to coordinate compression and Fenwick Tree operations). Space Complexity: O(n) for the auxiliary arrays and the Fenwick Tree.
Solution
The solution uses coordinate compression to map the potentially large numbers into a manageable range. Then, we use a Fenwick Tree to count the number of elements less than the current element while scanning the array.
- Compute a sorted list of unique values from nums and create a mapping (compression) for these values.
- Initialize a Fenwick Tree of appropriate size and iterate over nums from left to right. For each index i, query the tree to determine how many numbers that have already appeared are less than nums[i]. This gives the left count.
- Reset (or use another tree) and iterate over nums from right to left to compute the right count for each index.
- Finally, loop through the computed counts and count indices where both left and right counts are at least k.
A similar approach and data structure could be applied in any language that supports these operations.