Data Structures19 sections · 729 units
Open in Course

The Overlap Trick

Idempotent operations

To query range [l,r][l, r]:

1.1. Find the largest power of 2 that fits: k=log2(rl+1)k = \lfloor \log_2(r - l + 1) \rfloor

2.2. Take min\min of two overlapping ranges of length 2k2^k:

  • One starting at ll: st[l][k]\text{st}[l][k]
  • One ending at rr: st[r2k+1][k]\text{st}[r - 2^k + 1][k]
def query(l, r):
    length = r - l + 1
    k = int(log2(length))
    return min(st[l][k], st[r - (1 << k) + 1][k])

These two ranges cover [l,r][l, r] completely, possibly overlapping in the middle. Since min\min is idempotent, overlapping is fine.

Time: O(1)O(1) per query (with precomputed log\log values).