Skip to main content

Power Update After K-th Largest Insertion II - Solution & Explanation

HardPremiumFree on FleetCode6 min read
Practice this problem

Problem Statement

You are given an integer array nums and an integer p.

You are also given a 2D integer array queries, where each queries[i] = [vali, ki].

For each query:

  • Insert vali into nums.
  • Let x be the kith largest element in the current nums.
  • Update p to px % (109 + 7).

Return an array ans where the ans[i] represents the value of p after processing the ith query.

 

Example 1:

Input: nums = [2], p = 4, queries = [[3,1],[1,2]]

Output: [64,4096]

Explanation:

i vali Current
nums
ki kith
largest
p New p = pk % (109 + 7)
0 3 [2, 3] 1 3 4 43 % (109 + 7) = 64
1 1 [2, 3, 1] 2 2 64 642 % (109 + 7) = 4096

Thus, ans = [64, 4096].

Example 2:

Input: nums = [7,5], p = 6, queries = [[4,3],[7,2]]

Output: [1296,220296870]

Explanation:

i vali Current​​​​​​​
nums
ki kith
largest
p New p = pk % (109 + 7)
0 4 [7, 5, 4] 3 4 6 64 % (109 + 7) = 1296
1 7 [7, 5, 4, 7] 2 7 1296 12967 % (109 + 7) = 220296870

Thus, ans = [1296, 220296870]

 

Constraints:

  • 1 <= nums.length <= 2 * 104
  • 1 <= nums[i] <= 109
  • ​​​​​​​1 <= p <= 109
  • 1 <= queries.length <= 2 * 104
  • ​​​​​​​1 <= vali <= 109
  • 1 <= ki <= n + i + 1​​​​​​​

Approach Overview

Problem Overview: You receive a sequence of insertions and must continuously track the k-th largest element in the structure. After each insertion, a "power" value must be updated based on the current ordering of elements relative to that k-th largest threshold. A naive recomputation quickly becomes too slow as the dataset grows.

Approach 1: Re-sort After Every Insertion (Brute Force) (Time: O(n log n) per update, Space: O(n))

The simplest idea stores all inserted values in a list. After each insertion, sort the entire array and read the element at index n - k to obtain the k-th largest value. Once that value is known, recompute the power metric by iterating through the elements that influence the formula. This approach is easy to reason about and helps confirm correctness for small inputs. The downside is the repeated sort operation, which makes it impractical for large streams of updates.

Approach 2: Min Heap of Size K (Time: O(n log k), Space: O(k))

A more efficient approach maintains a min heap containing only the top k elements seen so far. The smallest element in the heap is always the current k-th largest. When a new value arrives, push it into the heap and remove the smallest element if the heap grows beyond size k. The heap root immediately gives the updated threshold needed to compute the power update. This technique relies on operations such as push and pop, each costing O(log k). Heaps are a common pattern in streaming problems involving order statistics and appear frequently in heap-based interview questions.

Approach 3: Fenwick Tree / Order Statistic Structure (Time: O(n log n), Space: O(n))

When the power update depends on aggregate information about many elements, maintaining only the k largest may not be enough. Instead, compress the value range and store frequencies in a Fenwick Tree (Binary Indexed Tree). Each insertion updates the frequency structure, and a binary search over prefix sums finds the index corresponding to the k-th largest value. Additional Fenwick trees or prefix sums can maintain sums needed for the power calculation. Each update and query runs in O(log n). This pattern is common in problems involving dynamic ranks and appears frequently alongside segment tree and binary search techniques.

Recommended for interviews: The min‑heap solution is usually the expected answer if the task only requires tracking the k-th largest element in a stream. It reduces the complexity from repeated sorting to O(n log k). If the power update depends on aggregated values across the dataset, interviewers often expect a Fenwick Tree or segment tree because it supports fast rank queries and prefix computations. Mentioning the brute force approach first shows baseline reasoning, while presenting the heap or Fenwick solution demonstrates algorithmic optimization skills.

Solution

We use a sorted list sl to maintain the current array nums. For each query, we insert val_i into sl, then find the k_i-th largest element x in sl. Using fast exponentiation, we update p to p^x bmod (10^9 + 7), and append the updated p to the answer array.

The time complexity is O((n + m) log (n + m)), and the space complexity is O(n + m), where n and m are the lengths of nums and queries, respectively.

Code

Python

C++

Try this approach in the editor β†’

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Re-sort after every insertionO(n log n) per updateO(n)Small inputs or verifying correctness during prototyping
Min heap of size kO(n log k)O(k)Streaming insertions where only the k-th largest threshold matters
Fenwick tree / order statistic treeO(n log n)O(n)Large datasets requiring rank queries and aggregated power calculations

Frequently Asked Questions

Is Power Update After K-th Largest Insertion II easy or hard?
Power Update After K-th Largest Insertion II is classified as a Hard problem because it combines streaming updates with order-statistic queries. Efficient solutions require familiarity with heaps, Fenwick trees, or segment trees and careful complexity management.
Power Update After K-th Largest Insertion II Python/Java solution
In Python, the solution typically uses the heapq module to maintain a min heap of size k. In Java, PriorityQueue provides the same behavior. For advanced implementations, Fenwick trees or segment trees are used to maintain dynamic order statistics.
How to solve Power Update After K-th Largest Insertion II in O(n log n)?
Use coordinate compression and maintain frequencies with a Fenwick Tree. Each insertion updates the tree in O(log n), and a binary search over prefix sums finds the k-th largest value. Additional prefix-sum queries compute any required power updates efficiently.
What is the best approach for Power Update After K-th Largest Insertion II?
The most practical solution maintains the k largest elements using a min heap of size k. Each insertion pushes a value into the heap and removes the smallest if the heap exceeds size k, keeping the root equal to the current k-th largest element. This keeps updates at O(log k) time while using O(k) space.
Is Power Update After K-th Largest Insertion II asked at Google/Amazon/Meta?
Problems involving maintaining the k-th largest element in a dynamic stream appear frequently in interviews at companies such as Google, Amazon, and Meta. Variations often combine heaps with additional data structures like segment trees or prefix sums to track extra metrics.
What data structure is used in Power Update After K-th Largest Insertion II?
Common choices include a min heap for tracking the top k elements and Fenwick Trees or segment trees for maintaining frequency counts and prefix sums. These structures support efficient rank queries and updates required after each insertion.
What is the time complexity of Power Update After K-th Largest Insertion II?
A brute force solution that sorts after every insertion costs O(n log n) per update. The optimized heap approach reduces this to O(log k) per insertion. If the power calculation requires aggregated statistics, Fenwick tree or segment tree solutions typically run in O(log n) per update.

Ready to solve this problem?

Practice Power Update After K-th Largest Insertion II with our built-in code editor and test cases.

Practice on FleetCode