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.

3 patterns · 24 problems · Java, Python, C++ and JavaScript

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

OperationTimeSpace
Overlap test for two intervalsO(1)O(1)
Sort n intervals by startO(n log n)O(log n) to O(n)
Merge or check conflicts after sortingO(n)O(n) for the output
Line sweep over 2n eventsO(n log n)O(n)
Difference array over times 0..TO(n + T)O(T)
Segment tree update or range queryO(log n)O(n)

Built into your language

Library calls
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

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.end instead of max(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: use Integer.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. 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. 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. 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