DSA · Pro · Pattern 5 of 9
Intervals & Sweep Line
12 problems.
Your progress0%
- 1st Visit
- 0/12
- 2nd Visit
- 0/12
- Revise
- 0/12
About this pattern
Interval problems describe ranges such as meetings, bookings, segments or trips. Sorting by start, or by end for greedy selection, brings overlapping ranges next to each other so they can be merged, intersected or counted in a single pass. A sweep line goes further: turn each interval into a +1 event at its start and a -1 event just after its end, sort the events, and scan them while keeping a running count. That count reveals the maximum overlap or the total length covered by exactly k intervals. A difference array does the same job when coordinates are small. Expect O(n log n) for sorting and linear work afterwards.
// Maximum number of closed intervals [l, r] that cover one point
int maxOverlap(const vector<pair<int, int>>& segs) {
vector<pair<int, int>> ev; // {coordinate, +1 or -1}
for (auto [l, r] : segs) {
ev.push_back({l, +1});
ev.push_back({r + 1, -1}); // the interval stops covering at r + 1
}
sort(ev.begin(), ev.end()); // -1 sorts before +1 at equal x
int cur = 0, best = 0;
for (auto [x, d] : ev) {
cur += d;
best = max(best, cur);
}
return best;
}