Skip to content

Lesson 29 of 40Advanced patterns

Intervals

Sort intervals by start to merge overlaps, and count how many overlap at once with a heap or a sweep line.

21 min read0/6 questions

Calendars, booking systems, video timelines, server maintenance windows, IP address ranges: each is a list of intervals, pairs of (start, end). Questions about them come up all the time. Which meetings clash? How many rooms do we need? What are the free slots?

Almost every interval problem starts with the same move: sort by start time. Once intervals are in order, overlaps can only happen between neighbours, and a single pass solves the problem.

When do two intervals overlap?

Take a = [a_start, a_end] and b = [b_start, b_end]. It is easier to say when they don't overlap: one ends before the other starts. Flip that, and they overlap exactly when:

a_start <= b_end and b_start <= a_end

Each must start before the other ends. If you have already sorted so that a starts first, this simplifies to one check: b_start <= a_end.

Whether touching intervals count ([1, 3] and [3, 5]) depends on the problem. For merging closed ranges they usually do (<=). For meetings that end at 3:00 and start at 3:00, they usually do not clash (<). Read the problem, and ask in an interview.

Quick check
Which pair does not overlap (treating touching ends as overlapping)?
Need a nudge? A hint rules out a wrong answer.

Merge overlapping intervals

Given [[6, 8], [1, 3], [2, 4], [7, 9]], merge every group of overlapping intervals.

  1. Sort by start.
  2. Start the output with the first interval.
  3. For each next interval: if it overlaps the last one in the output (start <= last_end), extend that one: last_end = max(last_end, end). Otherwise append it as a new interval.

Here is the timeline. Each row is an interval; filled cells are the times it covers.

Merging on a timeline (columns are time 0 to 9)
0123456789
■■■
■■■
■■■
■■■

The input, unsorted: [6,8], [1,3], [2,4], [7,9]. Overlaps are hard to see.

1/5
Python
def merge(intervals): intervals.sort(key=lambda iv: iv[0]) merged = [] for start, end in intervals: if merged and start <= merged[-1][1]: merged[-1][1] = max(merged[-1][1], end) # overlap: extend else: merged.append([start, end]) # gap: new interval return merged print(merge([[6, 8], [1, 3], [2, 4], [7, 9]]))print(merge([[1, 10], [2, 3], [4, 5]]))
Output
Press Run (⌘ Enter) to see what happens.

Sorting costs O(n log n) and the pass is O(n), so the total is O(n log n). The second example is why you need max: [1, 10] swallows [2, 3], and setting the end to 3 would shrink it.

Predict the outputPython

What does this print?

print(merge([[1, 4], [4, 5], [6, 7], [0, 2]]))
Need a nudge? Hints walk you through it.

How many rooms? Meeting rooms II

Now the question is how many intervals overlap at the busiest moment. That is the number of rooms you need. Meetings [[0, 30], [5, 10], [15, 20]] need 2 rooms: the long one, plus one room shared by the two short ones.

Min-heap approach. Sort meetings by start. Keep a min-heap of the end times of meetings currently using a room. For each meeting, if the earliest-ending room is free by its start (heap[0] <= start), reuse it (pop). Then push this meeting's end. The heap's largest size is the answer.

Python
import heapq def min_rooms(meetings): meetings.sort(key=lambda m: m[0]) ends = [] # end times of rooms in use rooms = 0 for start, end in meetings: if ends and ends[0] <= start: heapq.heappop(ends) # that room is free again heapq.heappush(ends, end) rooms = max(rooms, len(ends)) return rooms print(min_rooms([[0, 30], [5, 10], [15, 20]]))print(min_rooms([[1, 5], [5, 9], [9, 12]]))print(min_rooms([[1, 4], [2, 5], [3, 6]]))
Output
Press Run (⌘ Enter) to see what happens.

Sweep line approach. Forget which meeting is which. Turn every meeting into two events, +1 at its start and −1 at its end, and walk through time in order keeping a running count. The highest count is the answer. With separate sorted lists of starts and ends, it is two pointers, and it needs no heap at all, which is handy in JavaScript:

Python
def min_rooms_sweep(meetings): starts = sorted(s for s, _ in meetings) ends = sorted(e for _, e in meetings) rooms = best = j = 0 for s in starts: while ends[j] <= s: # meetings that ended by now free a room rooms -= 1 j += 1 rooms += 1 best = max(best, rooms) return best print(min_rooms_sweep([[0, 30], [5, 10], [15, 20]]))
Output
Press Run (⌘ Enter) to see what happens.

Both are O(n log n) because of sorting. The <= in ends[j] <= s encodes the rule that a meeting ending at 10 frees its room for one starting at 10. Change it to < and back-to-back meetings need separate rooms.

Put it in order4 steps

Order the steps of the min-heap meeting rooms solution, for each meeting.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/4 matched

Match the problem to the approach.

Choose an item, then its match on the other side.

Meeting rooms I: can one person attend everything?

The easy cousin of meeting rooms II asks a yes or no question: does any pair of meetings clash? Sort by start and compare each meeting with the next one only. If the next starts before this one ends (s2 < e1), there is a clash. You never need to compare meetings two apart. If meeting 1 runs into meeting 3, it also runs past the start of meeting 2, which sits between them, so the neighbour check already caught it.

Python
def can_attend(meetings): meetings = sorted(meetings) for (s1, e1), (s2, e2) in zip(meetings, meetings[1:]): if s2 < e1: # next starts before this one ends return False return True assert can_attend([[0, 30], [5, 10], [15, 20]]) is Falseassert can_attend([[7, 10], [2, 4]]) is Trueassert can_attend([[1, 5], [5, 9]]) is True # back to back is fineprint("all meeting rooms I checks pass")
Output
Press Run (⌘ Enter) to see what happens.

The strict < matches the meeting rule: ending at 5 and starting at 5 is not a clash. This is the "check neighbours" row from the matching exercise above.

Insert Interval: three phases

You have a calendar that is already sorted and already merged, and one new booking arrives. You could append it and rerun merge for O(n log n), but the input is sorted, so one O(n) pass is enough. The pass has three phases, and naming them out loud is half the solution.

  1. Before. Copy every interval that ends before the new one starts (end < new_start). They cannot touch it.
  2. Overlap. While the current interval starts at or before the new one's end (start <= new_end), absorb it: widen the new interval to the min of the starts and the max of the ends.
  3. After. Append the widened new interval, then copy the rest unchanged.
Insert [4, 8] into a sorted calendar
[1,2]
0
↑i
[3,5]
1
[6,7]
2
[8,10]
3
[12,16]
4
phase = beforenew = [4,8]

[1,2] ends at 2, before 4. It cannot touch the new interval: copy it to the output.

1/5
Python
def insert(intervals, new): start, end = new out, i, n = [], 0, len(intervals) # Phase 1: everything that ends before the new interval starts while i < n and intervals[i][1] < start: out.append(intervals[i]); i += 1 # Phase 2: everything that overlaps it gets absorbed while i < n and intervals[i][0] <= end: start = min(start, intervals[i][0]) end = max(end, intervals[i][1]) i += 1 out.append([start, end]) # Phase 3: everything after it, untouched out.extend(intervals[i:]) return out assert insert([[1, 3], [6, 9]], [2, 5]) == [[1, 5], [6, 9]]assert insert([], [5, 7]) == [[5, 7]]assert insert([[1, 5]], [6, 8]) == [[1, 5], [6, 8]]assert insert([[3, 5]], [0, 1]) == [[0, 1], [3, 5]]print(insert([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]))
Output
Press Run (⌘ Enter) to see what happens.

The edge cases interviewers test are all in the asserts: an empty list, a new interval after everything, one before everything. The three-phase shape handles each without special code, which is the real reason to write it this way instead of one loop full of flags.

Non-overlapping Intervals: sort by end, not start

"Remove the fewest intervals so the rest do not overlap" is the same as "keep as many as possible". That is the activity selection problem from Greedy Algorithms, and the trick is the sort key. Sort by end time, then walk through and keep any interval that starts at or after the end of the last one you kept. Count the rest as removed.

Why end time? The interval that ends first leaves the most room for everything after it. The exchange argument from Greedy Algorithms makes that precise. Take any optimal set of kept intervals and look at its first one. The earliest-ending interval overall finishes no later, so swapping it in cannot cause a clash with the second kept interval. The set stays the same size and stays valid. Repeat for the second, the third, and so on, and the greedy set is as large as the optimal one.

Sorting by start fails on one long interval that starts first. In [[1, 100], [2, 3], [4, 5], [6, 7]], a start-sorted greedy keeps [1, 100] and must then drop three. End-sorted greedy keeps the three short ones and drops only the long one.

Python
def erase_overlap_intervals(intervals): intervals = sorted(intervals, key=lambda iv: iv[1]) # by END kept_end = float("-inf") removed = 0 for start, end in intervals: if start >= kept_end: # fits after the last kept one (touching is fine) kept_end = end else: removed += 1 # clashes: drop it, keep the earlier-ending one return removed assert erase_overlap_intervals([[1, 2], [2, 3], [3, 4], [1, 3]]) == 1assert erase_overlap_intervals([[1, 2], [1, 2], [1, 2]]) == 2assert erase_overlap_intervals([[1, 2], [2, 3]]) == 0print(erase_overlap_intervals([[1, 100], [2, 3], [4, 5], [6, 7]]))
Output
Press Run (⌘ Enter) to see what happens.

Minimum Number of Arrows: the same greedy in disguise

Balloons are intervals on the x-axis. One arrow shot at x bursts every balloon with start <= x <= end. What is the fewest arrows? Sort by end. Shoot the first arrow at the end of the first balloon: that is as far right as you can go while still hitting it, so it catches the most balloons after it. Any balloon that starts after that x needs a new arrow, shot at its own end.

Python
def min_arrows(balloons): balloons = sorted(balloons, key=lambda b: b[1]) arrows = 0 arrow_x = float("-inf") for start, end in balloons: if start > arrow_x: # the last arrow misses this balloon arrows += 1 arrow_x = end # shoot as far right as this balloon allows return arrows assert min_arrows([[1, 2], [3, 4], [5, 6], [7, 8]]) == 4assert min_arrows([[1, 2], [2, 3], [3, 4], [4, 5]]) == 2print(min_arrows([[10, 16], [2, 8], [1, 6], [7, 12]]))
Output
Press Run (⌘ Enter) to see what happens.

Compare the two comparisons. Non-overlapping intervals uses start >= kept_end because touching intervals do not clash there. Arrows uses start > arrow_x because an arrow at x = 2 does burst a balloon that starts at 2. Same algorithm, opposite boundary rule. That one character is what interviewers watch for.

Predict the outputPython

What does this print?

print(min_arrows([[1, 2], [2, 3], [3, 4], [4, 5]]))
Need a nudge? Hints walk you through it.

Interval List Intersections: two pointers

Two people each send a sorted list of free slots, with no overlaps inside either list. When are they both free? Walk both lists with one pointer each, as in Two Pointers. At each step, the overlap of a[i] and b[j] is [max(starts), min(ends)], and it is real when lo <= hi. Then advance whichever interval ends first. It cannot overlap anything later in the other list, because everything later there starts after the current one ends.

Python
def intersect(a, b): i = j = 0 out = [] while i < len(a) and j < len(b): lo = max(a[i][0], b[j][0]) hi = min(a[i][1], b[j][1]) if lo <= hi: out.append([lo, hi]) # whoever ends first cannot meet anything else in the other list if a[i][1] < b[j][1]: i += 1 else: j += 1 return out A = [[0, 2], [5, 10], [13, 23], [24, 25]]B = [[1, 5], [8, 12], [15, 24], [25, 26]]assert intersect([[1, 3]], []) == []assert intersect([[1, 7]], [[3, 10]]) == [[3, 7]]print(intersect(A, B))
Output
Press Run (⌘ Enter) to see what happens.

This is O(m + n) with no sorting, because the inputs arrive sorted. The same shape answers "find a common free slot of at least 30 minutes": compute each intersection and check hi - lo >= 30.

Sweep line events and the tie-break

The sweep line in meeting rooms II used two sorted lists. The more general form builds one list of events, (time, +1) for each start and (time, -1) for each end, sorts them, and keeps a running total. It answers any "how many at once" question: peak concurrent users from session logs, the busiest minute, the year with the most people alive. Prefix Sums and Difference Arrays shows that this is a difference array over sorted event points.

The subtle part is ties. When one meeting ends at 10 and another starts at 10, which event goes first? If the start goes first, the count briefly shows both meetings live and you over-count rooms. With half-open intervals [start, end), ends must come first. Encoding the end as -1 and the start as +1 does this for free, because tuples compare their second item on ties and -1 < +1.

Python
def peak_overlap(meetings): events = [] for start, end in meetings: events.append((start, +1)) events.append((end, -1)) # On a tie, -1 sorts before +1: a room frees up before the next meeting takes it. events.sort() live = best = 0 for time, delta in events: live += delta best = max(best, live) return best def peak_overlap_starts_first(meetings): events = [(s, 0, +1) for s, _ in meetings] + [(e, 1, -1) for _, e in meetings] events.sort() # starts win ties: wrong for meetings live = best = 0 for _, _, delta in events: live += delta best = max(best, live) return best assert peak_overlap([[0, 30], [5, 10], [15, 20]]) == 2print(peak_overlap([[1, 5], [5, 9], [9, 12]]), peak_overlap_starts_first([[1, 5], [5, 9], [9, 12]]))
Output
Press Run (⌘ Enter) to see what happens.

If the problem uses closed intervals (a balloon touching at one point, a person counted as alive in both their birth year and death year), you want the opposite tie-break: starts before ends. Decide which kind of interval you have, then pick the order on purpose and say so.

Quick check
Meetings are [9, 10] and [10, 11], half-open (the first ends as the second starts). In a sweep line, which order for the two events at time 10 gives the correct room count?
Need a nudge? A hint rules out a wrong answer.

Common mistakes:

  • Forgetting to sort, or sorting by end when the algorithm needs start.
  • Setting last_end = end instead of max(last_end, end), which breaks on nested intervals.
  • Getting the touching case wrong (< versus <=). Decide it explicitly.
  • Mutating the caller's list with .sort() when they did not expect it. Use sorted() if that matters.
ChallengeMedium

Merge Intervals

Given a list of intervals [start, end], merge every group that overlaps and return the result sorted by start. Intervals that touch (one ends where the next starts) count as overlapping.

[[1, 3], [2, 6], [8, 10], [15, 18]]  →  [[1, 6], [8, 10], [15, 18]]
[[1, 4], [4, 5]]                     →  [[1, 5]]
[[4, 7], [1, 4]]                     →  [[1, 7]]   (input may be unsorted)

Constraints

  • 0 <= intervals.length <= 10^4
  • 0 <= start <= end <= 10^4
def merge(intervals: list[list[int]]) -> list[list[int]]: # Sort by start, then either extend the last merged interval or start a new one. pass
ChallengeMedium

Meeting Rooms II

Each meeting is a pair [start, end]. Return the minimum number of rooms needed so that every meeting gets a room. A room freed at time 10 can be used by a meeting that starts at 10.

[[0, 30], [5, 10], [15, 20]]  →  2
[[7, 10], [2, 4]]             →  1
[[1, 5], [5, 10]]             →  1   (back to back shares a room)

Constraints

  • 0 <= intervals.length <= 10^4
  • 0 <= start < end <= 10^6
def min_meeting_rooms(intervals: list[list[int]]) -> int: # Sweep through time: a start takes a room, an end gives one back. pass
Key terms
interval
A (start, end) pair describing a range of time or values.
overlap condition
Two intervals overlap when each starts before the other ends: a_start <= b_end and b_start <= a_end.
merge intervals
Sort by start, then extend the last merged interval with max(end) or start a new one.
sweep line
Turn intervals into +1 start and −1 end events, walk them in time order, and track the running count.
min-heap of end times
Tracks rooms in use; the root is the room that frees up soonest.
insert interval
Three phases over a sorted list: copy what ends before, absorb what overlaps, copy what comes after.
sort by end
The greedy order for keeping the most non-overlapping intervals or using the fewest arrows; the earliest end leaves the most room.
tie-break
The rule for events at the same time. For half-open intervals, process ends before starts.
Interview pattern: Intervals30 problemsSpot it: Meetings · overlapping ranges · insert a range