- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- 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.
Use this to learn the idea, then write your own version.
123 4from sortedcontainers import SortedList5 6 78class Solution(object):9 def powerUpdate(self, nums, p, queries):10 """11 :type nums: List[int]12 :type p: int13 :type queries: List[List[int]]14 :rtype: List[int]15 """16 MOD = 10**9+717 sl = SortedList(nums)18 result = []19 for x, k in queries:20 sl.add(x)21 p = pow(p, sl[-k], MOD)22 result.append(p)23 return result24 25 26272829class BIT(object): 30 def __init__(self, n):31 self.__bit = [0]*(n+1) 32 33 def add(self, i, val):34 i += 1 35 while i < len(self.__bit):36 self.__bit[i] += val37 i += (i & -i)38 39 def query(self, i):40 i += 1 41 ret = 042 while i > 0:43 ret += self.__bit[i]44 i -= (i & -i)45 return ret46 47 def kth_element(self, k):48 floor_log2_n = (len(self.__bit)-1).bit_length()-149 pow_i = 2**floor_log2_n50 total = pos = 0 51 for _ in reversed(xrange(floor_log2_n+1)): 52 if pos+pow_i < len(self.__bit) and not total+self.__bit[pos+pow_i] >= k:53 total += self.__bit[pos+pow_i]54 pos += pow_i55 pow_i >>= 156 return (pos+1)-157 58 59class Solution2(object):60 def powerUpdate(self, nums, p, queries):61 """62 :type nums: List[int]63 :type p: int64 :type queries: List[List[int]]65 :rtype: List[int]66 """67 MOD = 10**9+768 sorted_vals = sorted(set(nums)|set(x[0] for x in queries))69 val_to_idx = {x:i for i, x in enumerate(sorted_vals)}70 bit = BIT(len(val_to_idx))71 for x in nums:72 bit.add(val_to_idx[x], +1)73 result = []74 total = len(nums)75 for x, k in queries:76 bit.add(val_to_idx[x], +1)77 total += 178 i = bit.kth_element(total-k+1)79 p = pow(p, sorted_vals[i], MOD)80 result.append(p)81 return result82