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.
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.
Merge overlapping intervals
Given [[6, 8], [1, 3], [2, 4], [7, 9]], merge every group of overlapping intervals.
- Sort by start.
- Start the output with the first interval.
- 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.
The input, unsorted: [6,8], [1,3], [2,4], [7,9]. Overlaps are hard to see.
Press Run (⌘ Enter) to see what happens.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.
What does this print?
print(merge([[1, 4], [4, 5], [6, 7], [0, 2]]))
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.
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:
Press Run (⌘ Enter) to see what happens.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.
Order the steps of the min-heap meeting rooms solution, for each meeting.
- Tap the steps below in the right order.
Match the problem to the approach.
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.
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.
- Before. Copy every interval that ends before the new one starts (
end < new_start). They cannot touch it. - Overlap. While the current interval starts at or before the new one's end (
start <= new_end), absorb it: widen the new interval to theminof the starts and themaxof the ends. - After. Append the widened new interval, then copy the rest unchanged.
[1,2] ends at 2, before 4. It cannot touch the new interval: copy it to the 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.
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.
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.
What does this print?
print(min_arrows([[1, 2], [2, 3], [3, 4], [4, 5]]))
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.
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.
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.
[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?Common mistakes:
- Forgetting to sort, or sorting by end when the algorithm needs start.
- Setting
last_end = endinstead ofmax(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. Usesorted()if that matters.
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^40 <= start <= end <= 10^4
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^40 <= start < end <= 10^6
- 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.