Intervals · Lesson
Intervals, explained: overlap, merging and the line sweep
Learn interval problems: the overlap test, merging, greedy by end time and the line sweep, with templates in Java, Python, C++ and JavaScript and practice.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
The one test behind every interval problem
An interval is a pair [start, end]: a meeting, a booking, a range of days. Two intervals a and b overlap exactly when the later start is not after the earlier end: max(a.start, b.start) <= min(a.end, b.end). Every merge, conflict check and sweep below is this test in disguise.
Unsorted intervals are hard to reason about, because any pair might overlap. Sort by start and the picture becomes a line: an interval can only overlap the ones right before it, so one pass is enough. That sort, O(n log n), is usually the most expensive step.
Closed or half-open?
Read the problem for one detail: do touching intervals like [1, 3] and [3, 5] overlap?
- Closed
[start, end]: they share the point 3, so they overlap. Use<=in the test. Train platforms and day ranges usually work like this. - Half-open
[start, end): the first ends just as the second starts, so they do not overlap. Use<. Meetings and bookings usually work like this.
In a line sweep, the same choice decides the order of events at the same time: for half-open intervals, process ends before starts.
Merge, sweep or tree?
- Sort and scan when you merge, intersect or check for conflicts: compare each interval with the last one you kept.
- Line sweep when you ask "how many at once?": turn each interval into a +1 at its start and a −1 at its end, sort the events and keep a running count.
- Segment tree when intervals change between queries and you need the max or sum over a range in O(log n).
What it costs
| Operation | Time | Space |
|---|---|---|
| Overlap test for two intervals | O(1) | O(1) |
| Sort n intervals by start | O(n log n) | O(log n) to O(n) |
| Merge or check conflicts after sorting | O(n) | O(n) for the output |
| Line sweep over 2n events | O(n log n) | O(n) |
| Difference array over times 0..T | O(n + T) | O(T) |
| Segment tree update or range query | O(log n) | O(n) |
Built into your language
int[][] iv = {{5, 9}, {1, 3}, {2, 4}};
Arrays.sort(iv, (a, b) -> Integer.compare(a[0], b[0])); // by start
PriorityQueue<Integer> ends = new PriorityQueue<>(); // min-heap of end times
ends.offer(9); ends.peek(); ends.poll();
TreeMap<Integer, Integer> booked = new TreeMap<>(); // start -> end
booked.put(10, 20);
booked.floorEntry(15); // 10=20: the booking that starts at or before 15
booked.ceilingKey(15); // null: no booking starts at or after 15 iv = [[5, 9], [1, 3], [2, 4]]
iv.sort(key=lambda x: x[0]) # by start (plain iv.sort() also works: lists compare by start first)
import heapq
ends = [] # min-heap of end times
heapq.heappush(ends, 9); ends[0]; heapq.heappop(ends)
from bisect import bisect_right
starts = [1, 5, 10]
bisect_right(starts, 6) - 1 # 1: index of the last start <= 6 vector<vector<int>> iv = {{5, 9}, {1, 3}, {2, 4}};
sort(iv.begin(), iv.end()); // vectors compare by start first
priority_queue<int, vector<int>, greater<int>> ends; // min-heap of end times
ends.push(9); ends.top(); ends.pop();
map<int, int> booked; // start -> end, kept sorted
booked[10] = 20;
auto it = booked.upper_bound(15); // first booking that starts after 15
// prev(it) (if it != begin) is the booking that starts at or before 15 const iv = [[5, 9], [1, 3], [2, 4]];
iv.sort((a, b) => a[0] - b[0]); // by start
// JavaScript has no built-in heap or sorted map:
// sort an array of events, or write a small binary heap when you need one.
const events = [[1, 1], [3, -1], [2, 1]];
events.sort((a, b) => a[0] - b[0] || a[1] - b[1]); // by time, ends (-1) first Mistakes everyone makes
- Sorting by the wrong key: merging wants start order, "keep the most intervals" wants end order.
- Treating touching intervals inconsistently: decide closed or half-open once and use the same
<or<=everywhere. - Setting the merged end to
b.endinstead ofmax(a.end, b.end):[1, 10]swallows[2, 3]. - In a sweep, processing a start before an end at the same time when the intervals are half-open: that counts one overlap too many.
- Java comparators written as
a[0] - b[0]overflow for large or negative values: useInteger.compare.
The 3 patterns, in order
Each one: the idea and template, its variations with a worked example, then problems for you to solve.
- 1 Interval basics: overlap, merge, intersect and greedy Sort by start, then compare each interval with the last one you kept: extend it if they overlap, start a new one if not. Sort by end instead when you want to keep as many intervals as possible. 5 variations · 14 problems
- 2 Line sweep: count what overlaps at every moment Turn every interval into two events, +1 at the start and −1 at the end, sort them by time and keep a running total. The largest total is the most intervals that overlap at once. 6 variations · 9 problems
- 3 Segment tree: range queries while intervals change A segment tree keeps the max (or sum) of every block of positions, so you can change one position and ask about any range in O(log n). Use it when updates and range questions are mixed. 1 variation · 1 problem