- 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 find-x-value-of-array-ii.py.
- The implementation visibly relies on sequence storage.
- 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 45class Solution(object):6 def resultArray(self, nums, k, queries):7 """8 :type nums: List[int]9 :type k: int10 :type queries: List[List[int]]11 :rtype: List[int]12 """13 14 15 class SegmentTree(object):16 def __init__(self, N,17 build_fn=lambda _: None,18 query_fn=lambda x, y: y if x is None else x if y is None else max(x, y),19 update_fn=lambda x: x):20 self.tree = [None]*(1<<((N-1).bit_length()+1))21 self.base = len(self.tree)>>122 self.query_fn = query_fn23 self.update_fn = update_fn24 for i in xrange(self.base, self.base+N):25 self.tree[i] = build_fn(i-self.base)26 for i in reversed(xrange(1, self.base)):27 self.tree[i] = query_fn(self.tree[i<<1], self.tree[(i<<1)+1])28 29 def update(self, i, h):30 x = self.base+i31 self.tree[x] = self.update_fn(h)32 while x > 1:33 x >>= 134 self.tree[x] = self.query_fn(self.tree[x<<1], self.tree[(x<<1)+1])35 36 def query(self, L, R):37 L += self.base38 R += self.base39 left = right = None40 while L <= R:41 if L & 1:42 left = self.query_fn(left, self.tree[L])43 L += 144 if R & 1 == 0:45 right = self.query_fn(self.tree[R], right)46 R -= 147 L >>= 148 R >>= 149 return self.query_fn(left, right)50 51 def build(i):52 x = nums[i]%k53 cnt = [0]*(k+1)54 cnt[x] = 155 cnt[-1] = x56 return cnt57 58 def update(x):59 x %= k60 cnt = [0]*(k+1)61 cnt[x] = 162 cnt[-1] = x63 return cnt64 65 def query(x, y):66 if x is None:67 return y68 if y is None:69 return x70 cnt = x[:]71 for i in xrange(k):72 cnt[x[-1]*i%k] += y[i]73 cnt[-1] = x[-1]*y[-1]%k74 return cnt75 76 st = SegmentTree(len(nums), build_fn=build, update_fn=update, query_fn=query)77 result = [0]*len(queries)78 for idx, (i, v, s, x) in enumerate(queries):79 st.update(i, v)80 result[idx] = st.query(s, len(nums)-1)[x]81 return result82