- 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
- 61 lines of Python from the credited upstream file separate-squares-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 45class Solution(object):6 def separateSquares(self, squares):7 """8 :type squares: List[List[int]]9 :rtype: float10 """11 class SegmentTreeRecu(object):12 def __init__(self, sorted_x):13 self.sorted_x = sorted_x14 n = len(sorted_x)-115 l = 1<<((n-1).bit_length()+1)16 self.tree = [0]*l17 self.cnt = [0]*l18 19 def update(self, ql, qr, v, l, r, i): 20 if ql >= r or qr <= l:21 return22 if ql <= l and r <= qr:23 self.cnt[i] += v24 else:25 m = l+(r-l)226 self.update(ql, qr, v, l, m, 2*i)27 self.update(ql, qr, v, m, r, 2*i+1)28 if self.cnt[i] > 0:29 self.tree[i] = self.sorted_x[r]-self.sorted_x[l]30 else:31 if r-l == 1:32 self.tree[i] = 033 else:34 self.tree[i] = self.tree[2*i]+self.tree[2*i+1]35 36 events = []37 x_set = set()38 for x, y, l in squares:39 events.append((y, 1, x, x+l))40 events.append((y+l, -1, x, x+l))41 x_set.add(x)42 x_set.add(x+l)43 events.sort(key=lambda e: e[0])44 sorted_x = sorted(x_set) 45 x_to_idx = {x:i for i, x in enumerate(sorted_x)}46 st = SegmentTreeRecu(sorted_x)47 prev = events[0][0]48 intervals = []49 for y, v, x1, x2 in events:50 if y != prev:51 intervals.append([prev, y, st.tree[1]])52 prev = y53 st.update(x_to_idx[x1], x_to_idx[x2], v, 0, len(sorted_x)-1, 1)54 expect = sum((y2-y1)*curr for y1, y2, curr in intervals)/2.055 total = 0.056 for y1, y2, curr in intervals:57 if total+(y2-y1)*curr >= expect:58 break59 total += (y2-y1)*curr60 return y1+(expect-total)/curr61