Data Structures19 sections · 729 units
Open in Course

The Overlap Problem

Why brute force fails

Given nn intervals, answer qq queries of the form "which intervals contain point xx?" or "which intervals overlap with [l,r][l, r]?" Brute force: for each query, scan all nn intervals.

Time: O(nq)O(nq). For n=105n = 10^5 intervals and q=105q = 10^5 queries, that's 101010^{10} operations. Too slow. You need a data structure that:

1.1. Preprocesses intervals in O(nlogn)O(n \log n)

2.2. Answers overlap queries in O(logn+k)O(\log n + k) where kk is the result size

Interval trees achieve exactly this. Here's the trick: organize intervals by their midpoints to enable binary search.