Count the Number of K-Big Indices — LeetCode 2519 Python Solution
- Problem
- #2519
- Pattern
- Monotonic Stack
- Reading time
- 6 min
- Source
- leetcode.com
The problem
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 k different indices idx1 such that idx1 < i and nums[idx1] < nums[i].
Example
- Input
- nums = [2,3,6,5,2,3], k = 2
- Output
- 2
- Explanation
- There are only two 2-big indices in nums:
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n), where n is the length of the array auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 2519. Count the Number of K-Big Indices is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2519. Count the Number of K-Big Indices?
- LeetCode 2519. Count the Number of K-Big Indices is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2519. Count the Number of K-Big Indices?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2519. Count the Number of K-Big Indices?
- The Python solution on this page uses O(n), where n is the length of the array auxiliary space.
- What topics does LeetCode 2519. Count the Number of K-Big Indices cover?
- LeetCode 2519. Count the Number of K-Big Indices is tagged Binary Indexed Tree, Segment Tree, Array, Binary Search, Divide and Conquer, Ordered Set and Merge Sort on LeetCode.
- Is LeetCode 2519. Count the Number of K-Big Indices a premium problem?
- Yes. LeetCode 2519. Count the Number of K-Big Indices is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.