Problem solution · Python

Power Update After K Th Largest Insertion II

Power Update After K Th Largest Insertion II: a Python solution using segment tree or range structure. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Segment tree or range structure
Source
Kamyu LeetCode Solutions
Length
82 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Segment tree or range structure

For Power Update After K Th Largest Insertion II, the implementation stores interval information in a range-query data structure so updates and queries avoid rescanning the full input.

  1. Choose the aggregate stored for each interval or prefix.
  2. Build or initialize the structure from the input.
  3. Apply updates and combine the affected nodes to answer each query.

Code notes

  • 82 lines of Python from the credited upstream file power-update-after-k-th-largest-insertion-ii.py.
  • The implementation visibly relies on sequence storage, ordered lookup.
  • No explicit loop blocks detected.

Complexity

Count the build once, then multiply the logarithmic update or query path by the number of operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codePower Update After K Th Largest Insertion II · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O((n + q) * log(n * q) + q * logr)# Space: O(n + q) from sortedcontainers import SortedList  # sorted list, fast exponentiationclass Solution(object):    def powerUpdate(self, nums, p, queries):        """        :type nums: List[int]        :type p: int        :type queries: List[List[int]]        :rtype: List[int]        """        MOD = 10**9+7        sl = SortedList(nums)        result = []        for x, k in queries:            sl.add(x)            p = pow(p, sl[-k], MOD)            result.append(p)        return result  # Time:  O((n + q) * log(n * q) + q * logr)# Space: O(n + q)# sort, coordinate compression, fenwick tree, fast exponentiationclass BIT(object):  # 0-indexed.    def __init__(self, n):        self.__bit = [0]*(n+1)  # Extra one for dummy node.     def add(self, i, val):        i += 1  # Extra one for dummy node.        while i < len(self.__bit):            self.__bit[i] += val            i += (i & -i)     def query(self, i):        i += 1  # Extra one for dummy node.        ret = 0        while i > 0:            ret += self.__bit[i]            i -= (i & -i)        return ret       def kth_element(self, k):        floor_log2_n = (len(self.__bit)-1).bit_length()-1        pow_i = 2**floor_log2_n        total = pos = 0  # 1-indexed        for _ in reversed(xrange(floor_log2_n+1)):  # O(logN)            if pos+pow_i < len(self.__bit) and not total+self.__bit[pos+pow_i] >= k:                total += self.__bit[pos+pow_i]                pos += pow_i            pow_i >>= 1        return (pos+1)-1  class Solution2(object):    def powerUpdate(self, nums, p, queries):        """        :type nums: List[int]        :type p: int        :type queries: List[List[int]]        :rtype: List[int]        """        MOD = 10**9+7        sorted_vals = sorted(set(nums)|set(x[0] for x in queries))        val_to_idx = {x:i for i, x in enumerate(sorted_vals)}        bit = BIT(len(val_to_idx))        for x in nums:            bit.add(val_to_idx[x], +1)        result = []        total = len(nums)        for x, k in queries:            bit.add(val_to_idx[x], +1)            total += 1            i = bit.kth_element(total-k+1)            p = pow(p, sorted_vals[i], MOD)            result.append(p)        return result 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗