Problem solution · Python

Separate Squares II

Separate Squares 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
61 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 Separate Squares 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

  • 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.

Source

Code and credit

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

Full codeSeparate Squares II · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(nlogn)# Space: O(n) # sort, line sweep, segment treeclass Solution(object):    def separateSquares(self, squares):        """        :type squares: List[List[int]]        :rtype: float        """        class SegmentTreeRecu(object):            def __init__(self, sorted_x):                self.sorted_x = sorted_x                n = len(sorted_x)-1                l = 1<<((n-1).bit_length()+1)                self.tree = [0]*l                self.cnt = [0]*l                    def update(self, ql, qr, v, l, r, i):  # update [ql, qr) by v, interval [l, r) in sorted_x is covered by i                if ql >= r or qr <= l:                    return                if ql <= l and r <= qr:                    self.cnt[i] += v                else:                    m = l+(r-l)//2                    self.update(ql, qr, v, l, m, 2*i)                    self.update(ql, qr, v, m, r, 2*i+1)                if self.cnt[i] > 0:                    self.tree[i] = self.sorted_x[r]-self.sorted_x[l]                else:                    if r-l == 1:                        self.tree[i] = 0                    else:                        self.tree[i] = self.tree[2*i]+self.tree[2*i+1]            events = []        x_set = set()        for x, y, l in squares:            events.append((y, 1, x, x+l))            events.append((y+l, -1, x, x+l))            x_set.add(x)            x_set.add(x+l)        events.sort(key=lambda e: e[0])        sorted_x = sorted(x_set)         x_to_idx = {x:i for i, x in enumerate(sorted_x)}        st = SegmentTreeRecu(sorted_x)        prev = events[0][0]        intervals = []        for y, v, x1, x2 in events:            if y != prev:                intervals.append([prev, y, st.tree[1]])                prev = y            st.update(x_to_idx[x1], x_to_idx[x2], v, 0, len(sorted_x)-1, 1)        expect = sum((y2-y1)*curr for y1, y2, curr in intervals)/2.0        total = 0.0        for y1, y2, curr in intervals:            if total+(y2-y1)*curr >= expect:                break            total += (y2-y1)*curr        return y1+(expect-total)/curr 

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 ↗