- 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
- 77 lines of Python from the credited upstream file alternating-groups-iii.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 4from sortedcontainers import SortedList5 6 78class Solution(object):9 def numberOfAlternatingGroups(self, colors, queries):10 """11 :type colors: List[int]12 :type queries: List[List[int]]13 :rtype: List[int]14 """15 class BIT(object): 16 def __init__(self, n):17 self.__bit = [0]*(n+1)18 19 def add(self, i, val):20 i += 121 while i < len(self.__bit):22 self.__bit[i] += val23 i += (i & -i)24 25 def query(self, i):26 i += 127 ret = 028 while i > 0:29 ret += self.__bit[i]30 i -= (i & -i)31 return ret32 33 def update(i, d):34 if d == +1:35 sl.add(i)36 if len(sl) == 1:37 bit1.add(n, +1)38 bit2.add(n, +n)39 curr = sl.index(i)40 prv, nxt = (curr-1)%len(sl), (curr+1)%len(sl)41 if len(sl) != 1:42 l = (sl[nxt]-sl[prv]-1)%n+143 bit1.add(l, d*(-1))44 bit2.add(l, d*(-l))45 l = (sl[curr]-sl[prv])%n46 bit1.add(l, d*(+1))47 bit2.add(l, d*(+l))48 l = (sl[nxt]-sl[curr])%n49 bit1.add(l, d*(+1))50 bit2.add(l, d*(+l))51 if d == -1:52 if len(sl) == 1:53 bit1.add(n, -1)54 bit2.add(n, -n)55 sl.pop(curr)56 57 n = len(colors)58 sl = SortedList()59 bit1, bit2 = BIT(n+1), BIT(n+1)60 for i in xrange(n):61 if colors[i] == colors[(i+1)%n]:62 update(i, +1)63 result = []64 for q in queries:65 if q[0] == 1:66 l = q[1]67 result.append((bit2.query(n)-bit2.query(l-1))-68 (l-1)*(bit1.query(n)-bit1.query(l-1)) if sl else n)69 continue70 _, i, c = q71 if colors[i] == c:72 continue 73 colors[i] = c 74 update((i-1)%n, +1 if colors[i] == colors[(i-1)%n] else -1) 75 update(i, +1 if colors[i] == colors[(i+1)%n] else -1)76 return result77