Part 17 / Topic 14 of 20
Intervals
An interval is a range with a start and an end — a meeting, a booking, a sale window. Nearly every interval problem starts the same way: sort by start (or end), then sweep once, carrying a little state. Merging overlaps, inserting a booking, counting rooms — all O(n log n) for the sort plus O(n) for the sweep. Think of laying out overlapping meeting requests on a wall calendar: once they are in start order, you only ever compare each request with the one block you are currently building.
| Task | After sorting | State carried |
|---|---|---|
| merge overlapping ranges | one pass over neighbours | the block being built |
| insert one new range | copy before, absorb overlaps, copy after | the growing new range |
| rooms needed (max overlap) | sweep sorted starts and ends | count of meetings alive |
def merge_intervals(intervals):
ordered = sorted(intervals, key=lambda pair: pair[0])
merged = []
for start, end in ordered:
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end) # overlaps: extend
else:
merged.append([start, end]) # no overlap: new slot
return [tuple(pair) for pair in merged]
slots = [(9, 11), (10, 12), (13, 14), (14, 15), (18, 19)]
print(merge_intervals(slots)) # [(9, 12), (13, 15), (18, 19)]
The sweep: how many rooms does a day of meetings need? Sort the starts and the ends separately; walk them together, +1 room per start, −1 per end; the peak is the answer:
def rooms_needed(meetings):
starts = sorted(start for start, _ in meetings)
ends = sorted(end for _, end in meetings)
rooms = peak = s = e = 0
while s < len(starts):
if starts[s] < ends[e]:
rooms += 1; s += 1
peak = max(peak, rooms)
else:
rooms -= 1; e += 1
return peak
print(rooms_needed([(9, 11), (10, 12), (11, 13), (12, 14)])) # 2
Real-world example: merge_intervals is how a booking system turns a messy list of overlapping requested slots into the real busy periods, and rooms_needed is how it knows whether two meeting rooms are enough for Tuesday.
⚠️ Decide up front whether touching counts as overlapping —
(9, 11)and(11, 13)merge withstart <= last_endbut stay separate with<. Both are defensible; mixing them in one codebase is the bug.
Practice: merge overlapping intervals; insert one interval into a merged list; minimum rooms/platforms (peak overlap), and "remove fewest to make non-overlapping".
Practice on LeetCode - start here: Merge Intervals · Insert Interval · Non-overlapping Intervals · Summary Ranges
Show the full practice list (7 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Teemo Attacking | Easy |
| Interval List Intersections | Medium |
| Minimum Number of Arrows to Burst Balloons | Medium |
| My Calendar I | Medium |
| Queue Reconstruction by Height | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Minimum Interval to Include Each Query | Hard |
| Data Stream as Disjoint Intervals | Hard |
Full program: examples/14_intervals.py.
Exercise 14: Sorting — merge overlapping classroom bookings
Scenario: A coaching centre's rooms get double-booked; you need the real, merged list of busy time ranges per room.
What to do: Write merge_bookings(bookings: list[tuple[int, int]]) -> list[tuple[int, int]] (reuse the approach in examples/14_intervals.py's merge_intervals: sort by start, fold overlaps). Print the merged result for the data below.
Starting data:
BOOKINGS = [(9, 10), (9, 11), (11, 12), (13, 14), (13, 15), (16, 17)]
Sample output:
Bookings: [(9, 10), (9, 11), (11, 12), (13, 14), (13, 15), (16, 17)]
Merged: [(9, 12), (13, 15), (16, 17)]
Show the solution to Exercise 14
"""Exercise 14: Sorting - merge overlapping classroom bookings.
Run: python ex06.py (macOS/Linux: python3 ex06.py)
"""
BOOKINGS = [(9, 10), (9, 11), (11, 12), (13, 14), (13, 15), (16, 17)]
def merge_bookings(bookings: list[tuple[int, int]]) -> list[tuple[int, int]]:
ordered = sorted(bookings, key=lambda pair: pair[0])
merged: list[list[int]] = []
for start, end in ordered:
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return [tuple(pair) for pair in merged]
def main() -> None:
print("Bookings:", BOOKINGS)
print("Merged:", merge_bookings(BOOKINGS))
if __name__ == "__main__":
main()