Power Update After K-th Largest Insertion II Problem
Description
LeetCode Problem 3930.
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].
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^91 <= p <= 10^91 <= queries.length <= 2 * 10^41 <= val_i <= 10^91 <= k_i <= n + i + 1
Solution
Approach: Order Statistics
For each query we insert val and then need the k-th largest element x of the current array, which is the element at position size - k in sorted order. Then p = p^x mod (10^9 + 7) by fast exponentiation.
To keep the elements ordered we need "insert" and "k-th element" to be fast:
- In Python a sorted list with
bisect.insortis enough: inserting into a list of at most 4 * 104 numbers is a quick memory move. - In the other languages we count the values in a Fenwick tree over the compressed values (all of
numsand allvals, known in advance). Adding a value is a point update, and thej-th smallest value is found by descending the tree with binary lifting. Thek-th largest is the(size - k + 1)-th smallest.
Use 64-bit arithmetic (or BigInt in JavaScript) for the modular products.
Complexity: O((n + q) log (n + q)) time and O(n + q) extra space, where q is the number of queries.
from bisect import insort
class Solution:
def powerUpdate(self, nums: List[int], p: int, queries: List[List[int]]) -> List[int]:
mod = 10**9 + 7
sorted_nums = sorted(nums)
ans = []
for val, k in queries:
insort(sorted_nums, val)
p = pow(p, sorted_nums[-k], mod)
ans.append(p)
return ans