DDSA
  • Missions
  • Atlas
  • Lens
  • Lab
←
Atlas · Finishing techniques · Topic 16 of 18

Intervals

Sort intervals by start; then overlaps sit next to each other and one pass merges or counts them.

Spot it

Signals in the question

⌕Input is [start, end] pairs (meetings, bookings, ranges).

⌕"Merge", "insert", "remove the fewest" or "how many rooms".

⌕Two intervals overlap when one starts before the other ends.

The idea

O(n log n) time · O(n) space

Sort by start. Walk the list: if the next interval starts before the last merged one ends, they overlap, so stretch the end. Otherwise start a new merged interval.

Template · Sort, then sweep

1def merge(intervals):2    intervals.sort(key=lambda i: i[0])3    merged = []4    for start, end in intervals:5        if merged and start <= merged[-1][1]:6            merged[-1][1] = max(merged[-1][1], end)   # overlap: stretch7        else:8            merged.append([start, end])9    return merged

The template, filled in for Merge Intervals. The highlighted lines are the part every problem of this kind shares.

The best, free

One of each
▶︎WatchIntervals, explainedNeetCode · YouTube · free↗¶ReadMerging intervalsGeeksforGeeks · free↗

Practice set

Loading your mission…

Common mistakes

1Forgetting to sort first: overlaps aren't next to each other otherwise.

2Setting the end to the new interval's end instead of the max of both.

3Mixing up whether touching intervals ([1,4] and [4,5]) count as overlapping.

Check yourself

Question 1 of 2

When do [a, b] and [c, d] overlap (sorted so a ≤ c)?