Power Update After K-th Largest Insertion I Problem
Description
LeetCode Problem 3935.
You are given an integer array nums and an integer p.
You are also given a 2D integer array queries, where each queries[i] = [val_i, k_i] and the difference between consecutive k_i values is always less than 10.
For each query:
- Insert
val_iintonums. - Let
xbe thek_i^thlargest element in the currentnums. - Update
ptop^x % (10^9 + 7).
Return an array ans where the ans[i] represents the value of p after processing the i^th query.
Example 1:
Input: nums = [2], p = 4, queries = [[3,1],[1,2]]
Output: [64,4096]
Explanation:
i val_i Current nums k_i k_i^th largest p New p = p^k % (10^9 + 7)
0 3 [2, 3] 1 3 4 4^3 % (10^9 + 7) = 64
1 1 [2, 3, 1] 2 2 64 64^2 % (10^9 + 7) = 4096
Thus, ans = [64, 4096].
Example 2:
Input: nums = [7,5], p = 6, queries = [[4,3],[7,2]]
Output: [1296,220296870]
Explanation:
i val_i Current nums k_i k_i^th largest p New p = p^k % (10^9 + 7)
0 4 [7, 5, 4] 3 4 6 6^4 % (10^9 + 7) = 1296
1 7 [7, 5, 4, 7] 2 7 1296 1296^7 % (10^9 + 7) = 220296870
Thus, ans = [1296, 220296870]
Constraints:
1 <= nums.length <= 2 × 10^41 <= nums[i] <= 10^61 <= p <= 10^61 <= queries.length <= 2 × 10^41 <= val_i <= 10^61 <= k_i <= n + i + 1|k_i - k_(i - 1)| < 10fori > 0
Solution
Approach: Fenwick Tree and Fast Exponentiation
Each query needs the k-th largest value after an insertion, which is the (size - k + 1)-th smallest value. Values are at most 106, so we keep a Fenwick tree (binary indexed tree) of counts indexed by value.
For every query:
- Add
valto the tree and increase the size by one. - Find the (size - k + 1)-th smallest value
xby walking down the tree from the highest power of two: jump forward whenever the block at that position still holds fewer than the wanted number of items, and subtract what we skipped. - Update
pwith fast modular exponentiation:p = p^x % (10^9 + 7), and append it to the answer.
The condition on consecutive k_i values is not needed with this approach, because a Fenwick tree answers any rank in logarithmic time.
Complexity: O((n + m) log V) time and O(V) space, where n and m are the lengths of nums and queries and V = 106 is the largest value. Each exponentiation costs O(log V) more.
class Solution:
def powerUpdate(
self, nums: List[int], p: int, queries: List[List[int]]
) -> List[int]:
mod = 10**9 + 7
m = 10**6
tree = [0] * (m + 1)
def add(i: int) -> None:
while i <= m:
tree[i] += 1
i += i & -i
def kth_smallest(k: int) -> int:
pos = 0
step = 1 << 19
while step:
if pos + step <= m and tree[pos + step] < k:
pos += step
k -= tree[pos]
step >>= 1
return pos + 1
for x in nums:
add(x)
total = len(nums)
ans = []
for val, k in queries:
add(val)
total += 1
x = kth_smallest(total - k + 1)
p = pow(p, x, mod)
ans.append(p)
return ans