Intervals: merge, cover and schedule

125 min8 partsCoreFundamentalsChecked Nov 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Choose closed or half-open ends on purpose, test two intervals for overlap with one rule, and turn a set of days into runs of days in a row
  • Sort by start and merge in one pass, insert one interval into a sorted list, and find free time as the gaps between busy times
  • Count the most intervals open at once with a sweep over starts and ends, settle a tie at one instant on purpose, and say how a heap of end times gets the same answer
  • Split a range between two people with one comparison per pair, and cover it with the fewest intervals by a greedy choice you can defend
  • Try every set smallest first with itertools.combinations, rank the sets with one tuple key, and say when trying every set stops being possible
  • Answer the follow-ups: bookings that arrive one at a time, jobs that can't overlap, a calendar as the bits of one integer, real dates and time zones, and a trip that needs more than two stays
Part 1 of 8about 2 min
The problem

Split stays and group stays

This lesson teaches intervals, stretches of time with a start and an end, and you'll use them to build a stays search. Airbnb candidates report two questions about listings and the nights they're free. One is a split stay, two listings that together cover a trip (3 sources). The other is a group stay, listings chosen so their capacities fit a group (2 reports). Here they're one problem in levels, and level 1 starts with a statement like this one:

listings maps each listing's name to a dict of its details: free, the nights it's free, capacity, how many guests it sleeps, and neighborhood. For example, {"loft": {"free": [1, 2, 3], "capacity": 2, "neighborhood": "Mission"}}. A trip runs from night start through night end, both included.

Write split_stays(listings, start, end). It returns every pair (first, second) of different listings where a guest can sleep at first from night start through some night k, then at second from night k + 1 through end, with at least one night at each.

  • A pair appears once, however many nights k would work. (first, second) and (second, first) are different trips, and the list is sorted.
  • A listing that's free for the whole trip is in no pair: the guest would just book it.
  • A one-night trip has no splits.
ListingFree nights
loft1, 2, 3
barn3, 4, 5
cabin1, 2
dome4, 5
yurt1, 2, 3, 4, 5

split_stays(listings, 1, 5) returns these three pairs, in this order:

firstsecondLast night at first
cabinbarn2
loftbarn2 or 3
loftdome3

split_stays(listings, 2, 2) returns [].

cabin and dome don't pair, because nobody covers night 3. yurt is in no pair, because it's free for the whole trip.

Two more levels fit a group, and you solve all three at the end

Level 2 is the group stay: given a group size and a neighborhood, pick listings whose capacities add up to fit everyone, with the fewest listings first, then the least total capacity, then the names. Level 3 returns a page of options, ranked the same way, from only the listings free for the whole trip, and every listing in an option has to be needed.

You don't write it yet. First you learn what the end of an interval means, how to merge and sweep intervals, how two people split a range, and how to pick the best set. At the end you solve the whole problem, level by level, in an interview simulation with a 60-minute timer.

This lesson builds on the heaps lesson: merging intervals starts with a sort, and counting the rooms in use keeps a heap of end times. Its half-open windows, where the start is in and the end is out, are the same ones the database uses for expiry in the coding builds, where small systems grow in levels.

Part 1 done
Part 2 of 8about 18 min
What an end means

Decide what the end of an interval means

Interval questions ask how stretches of time, each a start and an end, sit against each other:

  • Do these two meetings clash?
  • Which hours is nobody busy?
  • How many rooms are in use at the worst moment?
  • Can two people's free days cover a whole rotation?

They show up on the companies' lists. Merge Intervals and Meeting Rooms II are on Netflix's LeetCode tag list (2 sources), and Employee Free Time is on Airbnb's (1 source). The split stays from the start of the lesson are one more.

This lesson builds the pieces one at a time, and ends back at the split stays. The first piece is a choice you make before any code: what the end of an interval means.

Half-open hours stop just before the end, so back-to-back meetings share a number

Predict

Two meetings, (9, 10) and (10, 11), as half-open hours. Do they overlap?

Pick an answer above to see the rest

Closed nights include both ends, so the next stay starts the night after

Meetings end at an instant. Hotel stays are counted in whole nights, and that changes what the end means.

Predict

A stay covers nights 10 through 12, closed. What's the first night the next stay can start?

Pick an answer above to see the rest

Two half-open intervals overlap when each one starts before the other ends

Most interval questions come down to one test: do two intervals overlap?

# half-open: (start, end)
def overlaps(a, b):
    return a[0] < b[1] and b[0] < a[1]


cases = {
    "apart": ((1, 3), (5, 7)),
    "touching": ((1, 4), (4, 7)),
    "crossing": ((1, 5), (3, 7)),
    "inside": ((3, 5), (1, 7)),
}
for name, (a, b) in cases.items():
    print(name, overlaps(a, b))
apart False
touching False
crossing True
inside True

Here are the four cases on one line of time:

The four cases
apart: a
apart: b False
touching: a
touching: b False
crossing: a
crossing: b True
inside: a
inside: b True
02468

The test comes from its opposite. Two intervals don't overlap exactly when one is over by the time the other starts: a_end <= b_start or b_end <= a_start. Negate both sides and you get the one test. Each interval must start before the other ends.

For closed ends, both < become <=, since sharing an end day is sharing a day.

Both tests assume each interval holds something: start < end for half-open, start <= end for closed. The empty closed (5, 3) passes the closed test against (1, 7).

In the editor, write shifts_overlap(a, b): the overlap test for on-call shifts in closed days, where two shifts that share an end day overlap.

The test that checks where the ends fall misses an interval inside another

There is a second way to write the overlap test that looks just as right. It isn't.

# does an end of b fall inside a?
def an_end_inside(a, b):
    return a[0] <= b[0] < a[1] or a[0] < b[1] <= a[1]


print(an_end_inside((3, 5), (1, 7)))

spans = [(s, e) for s in range(8) for e in range(8) if s < e]
pairs = [(a, b) for a in spans for b in spans]
wrong = [(a, b) for a, b in pairs if an_end_inside(a, b) != overlaps(a, b)]
print(len(spans), len(pairs), len(wrong))
print(all(b[0] < a[0] and a[1] < b[1] for a, b in wrong))
Predict

an_end_inside(a, b) asks whether an end of b falls inside a. What does an_end_inside((3, 5), (1, 7)) return?

Pick one to see what it prints.
Pick an answer above to see the rest

Sorted, with repeats dropped, free days become runs of days in a row

An on-call engineer is free on days {3, 4, 5, 8, 9, 12}. Free time often comes like this, as a set of days rather than as intervals. The question you'll keep asking is which stretches of days in a row that makes.

Predict

Free days {3, 4, 5, 8, 9, 12}. How many runs of days in a row do they make?

Pick an answer above to see the rest
Part 2 done
Part 3 of 8about 15 min
Merging

Sort by start, and one pass merges

Three questions run on the same pass over intervals sorted by start: merge them, insert one more, and find the gaps between them.

Sorted by start, a block can only overlap the merged block just before it

Three people's calendars, in half-open hours:

ana = [(9, 10), (12, 15)]
bo = [(10, 11), (12, 13), (16, 17)]
cy = [(13, 14), (15, 16)]


def merge(blocks):
    out = []
    for start, end in sorted(blocks):
        # starts by the time the last one ends
        if out and start <= out[-1][1]:
            out[-1][1] = max(out[-1][1], end)
        else:
            out.append([start, end])
    return out


print(merge(ana + bo + cy))
Predict

The busy blocks are (9, 10), (10, 11), (12, 13), (12, 15), (13, 14), (15, 16) and (16, 17), merged when they overlap or touch. How many blocks are left?

Pick one to see what it prints.
Pick an answer above to see the rest

Whether touching blocks merge depends on the question

Look at ana's (9, 10) and bo's (10, 11) in the figure. They touch at 10, and the merge joined them into (9, 11), because its test is <=.

  • That's right when the question is when someone is busy. There's no free moment between them.
  • It's wrong when you count clashes, because they don't overlap. There, test with <, and touching blocks stay apart.
  • For closed days, (3, 5) and (6, 8) leave no day between them. So merging runs of days uses start <= last_end + 1.

Decide which one the question wants before you write the comparison.

In the editor, write the loop of merge_days(runs): merge closed runs of days that overlap or sit back to back, so (3, 5) and (6, 8) become (3, 8).

Inserting one block into a sorted calendar is O(n), with no new sort

A calendar holds disjoint busy blocks, sorted. A new block arrives. You don't need to sort again. Copy the blocks that end before it starts, swallow every block that overlaps it into one, then copy the rest:

def insert(blocks, new):
    start, end = new
    out, i = [], 0
    # ends before the new one starts
    while i < len(blocks) and blocks[i][1] < start:
        out.append(blocks[i])
        i += 1
    # overlaps or touches it: swallow
    while i < len(blocks) and blocks[i][0] <= end:
        start, end = min(start, blocks[i][0]), max(end, blocks[i][1])
        i += 1
    out.append((start, end))
    # starts after it ends
    out.extend(blocks[i:])
    return out


blocks = [(1, 3), (5, 7), (9, 12), (14, 16)]
print(insert(blocks, (6, 10)))
print(insert(blocks, (3, 4)))
Predict

Insert (6, 10) into the sorted blocks (1, 3), (5, 7), (9, 12) and (14, 16). How many blocks are there after?

Pick one to see what it prints.
Pick an answer above to see the rest

Free time is the gaps, found with one number that only moves later

Take the same three calendars and a working day from 8 to 18. Merged, everyone's busy blocks are (9, 11) and (12, 17). So the free time is (8, 9), (11, 12) and (17, 18). That's Employee Free Time.

You don't need the merged list itself. Walk the blocks in start order and keep one number, free_from. Everything before it is busy or already reported.

  • A block that starts after free_from leaves a gap.
  • Every block pushes free_from out to its end, if its end is later.
Block, in start orderGap it leavesfree_from after it
8, the start of the day
(9, 10)(8, 9)10
(10, 11)11
(12, 13)(11, 12)13
(12, 15)15
(13, 14)15
(15, 16)16
(16, 17)17
the end of the day(17, 18)

Watch the row for (13, 14). Its end, 14, is earlier than free_from, so free_from stays at 15.

When each person's calendar already comes sorted, you don't need to sort them all together either. The heaps lesson's merge of k sorted streams, heapq.merge(ana, bo, cy), hands out the blocks in start order in O(N log k) for N blocks across k people.

One slip breaks the walk: setting free_from to the block's end instead of the later end. Then a block inside another drags free_from back:

Free time from 12 to 17, two ways
(12, 15)
(13, 14)
(15, 16)
free, with max
free, with end inside (12, 15)
free, with end
121314151617

In the editor, write the loop of free_time(busy, day_start, day_end): walk everyone's busy blocks in start order with free_from, and collect the gaps in gaps.

CheckpointFree time is the gaps

busy holds everyone's meetings as half-open (start, end) hours, several calendars mixed together, in any order, all inside the day from day_start to day_end. Finish free_time(busy, day_start, day_end): the times nobody is busy, as half-open (start, end) gaps in order, with no empty gaps such as (10, 10).

Watch · 9 min

Merge Intervals, the question on Netflix's tag list, explained with a drawing, then coded in Python from 5:40.

Merge Intervals - Sorting - Leetcode 56 · NeetCode · Jan 2021YouTube
Part 3 done
Part 4 of 8about 17 min
The sweep

Count the most intervals open at once with a sweep

A pool of machines takes reservations in half-open hours. How many machines does it need? That's the most reservations open at the same moment, the question Meeting Rooms II asks.

Counting the overlaps of each interval can give too many

res = [(1, 10), (1, 2), (5, 6)]
for a in res:
    print(a, 1 + sum(overlaps(a, b) for b in res if b != a))
(1, 10) 3
(1, 2) 2
(5, 6) 2

The obvious answer counts, for each reservation, how many others overlap it. Then it takes the largest count, plus one for the reservation itself. It's O(n²), and it's wrong.

The long reservation overlaps both short ones, so it scores 3.

Predict

Reservations (1, 10), (1, 2) and (5, 6). What's the most open at any one moment?

Pick an answer above to see the rest

The sweep turns each interval into +1 at its start and -1 at its end

Checking every moment works only while the times are small whole numbers. A sweep looks only at the moments where something changes.

def most_at_once(reservations):
    events = []
    for start, end in reservations:
        events.append((start, 1))
        events.append((end, -1))
    # by time, and at one time -1 sorts before +1
    events.sort()
    now = most = 0
    for _, change in events:
        now += change
        most = max(most, now)
    return most


R = [(1, 4), (2, 5), (3, 4), (4, 7), (5, 8)]
print(most_at_once(R))
3

The sweep looks at moments instead of pairs. Picture a line that moves from left to right across the timeline. Each start it crosses adds 1 to a running count, and each end takes 1 off. The count is how many reservations are open right there, and the largest count is the answer:

The sweep line at 4
the sweep line
(1, 4) ends at 4
(2, 5)
(3, 4) ends at 4
(4, 7) starts at 4
(5, 8)
02468

Open just after each time from 1: 1, 2, 3, 2, 2, 2, 1, 0. The most is 3, from 3 to 4.

The peak is 3, at time 3. The cost is the sort: O(n log n) time, and O(n) memory for the 2n events.

In the editor, write open_after(res): build the +1 and -1 events, sort them, and record in counts how many reservations are open after each event.

On half-open times, an end goes before a start at the same instant

At time 4 in the figure, two reservations end and one starts. Here are all the events, in the order the sort puts them:

TimeEventOpen after it
1start of (1, 4)1
2start of (2, 5)2
3start of (3, 4)3
4end of (1, 4)2
4end of (3, 4)1
4start of (4, 7)2
5end of (2, 5)1
5start of (5, 8)2
7end of (4, 7)1
8end of (5, 8)0

Half-open says the ones that end at 4 are already over when the one at 4 begins. So the ends must go first. The events are tuples, and tuples sort field by field. So at one time, (4, -1) comes before (4, 1) with no extra code.

Process the starts first instead, as a key of (time, -change) does, and see what happens:

def peak(events, key=None):
    now = most = 0
    for _, change in sorted(events, key=key):
        now += change
        most = max(most, now)
    return most


events = [(s, 1) for s, e in R] + [(e, -1) for s, e in R]
# ends first
print(peak(events))
# starts first
print(peak(events, key=lambda e: (e[0], -e[1])))
3
4

With starts first, the count climbs to 4 at time 4 before the ends come off. The function reports 4 machines where 3 are enough.

In the editor, write busiest(reservations): the sweep, returning the most reservations open at once and the earliest time that many are open, with ends before starts at one instant.

CheckpointEnds before starts

Each reservation holds a machine for half-open hours start <= t < end, and they come in any order. Finish busiest(reservations): return (most, when), the most reservations active at once and the earliest time that many are active, or (0, None) when there are none. A reservation that ends at 4 and one that starts at 4 don't overlap.

On closed days, a start goes first, or each end moves to the day after

Starts first isn't always wrong. It means that two intervals that share an instant both hold it, and that's what closed ends mean. On-call shifts (3, 5) and (5, 7), in closed days, both hold day 5. There, ends first is the bug. Either put starts first, or put each -1 at end + 1, so the shift (3, 5) is over at day 6:

# closed days: both hold day 5
shifts = [(3, 5), (5, 7)]
same_day = [(s, 1) for s, e in shifts] + [(e, -1) for s, e in shifts]
day_after = [(s, 1) for s, e in shifts] + [(e + 1, -1) for s, e in shifts]
# ends first
print(peak(same_day))
# starts first
print(peak(same_day, key=lambda e: (e[0], -e[1])))
# each end moved to end + 1
print(peak(day_after))
1
2
2

On 3,000 random sets of closed shifts, starts first and end + 1 both matched a count of every day. So the tie rule says what your ends mean:

  • Ends first: touching intervals don't overlap. That's half-open.
  • Starts first: touching intervals overlap. That's closed.

In the editor, most_on_one_day(shifts) runs the sweep on closed shifts. In its first loop, write the two events for each shift, with the end moved to the day after the shift's last day.

A min-heap of end times and two sorted lists give the same count

A min-heap of the end times of the rooms in use gets the same answer. The heaps lesson's version pops every end at or before each start, then pushes the new end. The most end times the heap ever holds at once is the answer. Its ends[0] <= start is the same tie rule as ends going first here.

A third form skips the tuples. Sort the starts and the ends as two lists of plain numbers, and walk both. Here are both, the heap first:

import heapq


def most_at_once_heap(meetings):
    # end times of the rooms in use
    ends, most = [], 0
    for start, end in sorted(meetings):
        while ends and ends[0] <= start:
            heapq.heappop(ends)
        heapq.heappush(ends, end)
        most = max(most, len(ends))
    return most


def most_at_once_two_lists(meetings):
    starts = sorted(s for s, _ in meetings)
    ends = sorted(e for _, e in meetings)
    now = most = j = 0
    for s in starts:
        # ends at or before this start come first
        while ends[j] <= s:
            j += 1
            now -= 1
        now += 1
        most = max(most, now)
    return most


for meetings in (R, [(1, 4), (4, 7), (7, 9)]):
    print(most_at_once(meetings), most_at_once_heap(meetings), most_at_once_two_lists(meetings))
3 3 3
1 1 1

All three agreed on 100,000 random meetings, built with random.Random(7). Each starts at a random hour from 0 to 100,000 and lasts a random 1 to 200 hours, or 1 to 2,000:

Longest meetingAnswerHeap of end timesEvents as tuplesTwo sorted lists
20014147.4 ms75.4 ms37.4 ms
2,0001,08953.5 ms84.6 ms40.3 ms

Best of 5 runs, Python 3.12, on the laptop these numbers come from. All three are O(n log n). The two lists sort plain integers, which is cheaper than sorting 200,000 tuples.

Reach for the events version when events carry more than plus or minus one. A reservation for 3 machines is +3 and -3, and different kinds of event can share one sorted list.

When times are small integers, like the 1,440 minutes of a day, you can skip the sort. Keep a list of counts, one slot per minute. Add 1 at each start, subtract 1 at each end, and keep a running sum: O(n + T) for T time slots.

In the editor, each reservation is a half-open (start, end, k) that holds k machines. In machines_needed(res), write the events, +k at the start and -k at the end, and the sweep below them does the rest.

Watch · 10 min

Meeting Rooms II, also on Netflix's tag list, explained with a drawing, then coded in Python from 8:43.

Meeting Rooms II - Leetcode 253 - Python · NeetCode · May 2021YouTube
Part 4 done
Part 5 of 8about 14 min
Two people

Cover a range with two people

An on-call rotation runs from day 1 through day 7, closed. Only one person is free all week, so you want handoffs as well. One engineer takes day 1 through some day k, and another takes day k + 1 through day 7. Which ordered pairs can do that?

The slow answer tries every pair, every handoff day and every day

Here's who is free when:

ONCALL = {
    "ana": {1, 2, 3, 6, 7},
    "bo": {3, 4, 5, 6, 7},
    "cy": {1, 2, 3, 4},
    "dev": {2, 3, 4, 5, 6, 7},
    "eli": {1, 2, 3, 4, 5, 6, 7},
    "fay": {1, 5, 6, 7},
}

The slow answer tries every handoff day. For a pair, a then b, the handoff day k runs from start up to end - 1, so each person gets at least one day. A k works when a is free on every day from start through k, and b on every day from k + 1 through end. Checking those days one at a time is what makes it slow.

For cy then fay, day 4 works: cy covers days 1 through 4, and fay covers 5 through 7. For ana then fay, no day works, because neither of them is free on day 4.

Here is the same calendar as a grid, with an x on each free day:

Who is free on each day
free
1234567anaxxxxxboxxxxxcyxxxxdevxxxxxxelixxxxxxxfayxxxx

The slow answer tries every pair, every handoff day, and every day in each part. For m engineers and a rotation of L days, that's m² pairs times L handoff days times L days checked: O(m² L²).

In the editor, a and b are the sets of days two people are free. Write handoff_days_slow(a, b, start, end): every handoff day k that works, checked day by day.

From each person, a pair needs only two numbers: reach and begins

Look at what a pair actually needs from each person:

  • From the first, only how far their free run from day 1 reaches. Call it reach.
  • From the second, only where their free run into day 7 begins. Call it begins.

Both come straight out of the runs of free days you built with runs. reach is the end of the run that holds start, but no later than end. begins is the start of the run that holds end, but no earlier than start.

Someone not free on day 1 gets reach = start - 1, 0 here. Someone not free on day 7 gets begins = end + 1, 8 here. Those values make the comparisons below fail on their own, with no special case.

Runsreachbegins
ana(1, 3), (6, 7)36
bo(3, 7)03
cy(1, 4)48
dev(2, 7)02
eli(1, 7)71
fay(1, 1), (5, 7)15

In the editor, runs is the function you wrote for free days, filled in. Write reach_and_begin(days, start, end): from someone's free days, how far their run from start reaches, and where their run into end begins.

CheckpointHow far the run from the start reaches

A rotation runs from day start through day end, both included, and days is the set of days someone is free, possibly empty. Finish reach_and_begin(days, start, end) using runs, which you wrote for free days earlier. reach is the last day, at most end, such that they're free every day from start through it, or start - 1 if they aren't free on start. begins is the first day, at least start, such that they're free every day from it through end, or end + 1 if they aren't free on end.

The handoff day has to fit two windows at once

The handoff day k is the first person's last day. It has to pass three checks:

  • Each person works at least one day, so start <= k <= end - 1.
  • The first is free every day through k, so k <= reach_a.
  • The second is free from k + 1 on, so k >= begins_b - 1.

So k lies in two closed intervals at once, (start, end - 1) and (begins_b - 1, reach_a). Take the later start and the earlier end. The pair works when that window isn't empty:

# a and b are (reach, begins) pairs
def handoff_days(a, b, start, end):
    reach_a, _ = a
    _, begins_b = b
    first, last = max(start, begins_b - 1), min(end - 1, reach_a)
    return (first, last) if first <= last else None


# from the table
RB = {"ana": (3, 6), "bo": (0, 3), "cy": (4, 8), "fay": (1, 5)}
for first, second in [("cy", "bo"), ("cy", "fay"), ("ana", "fay")]:
    print(first, second, handoff_days(RB[first], RB[second], 1, 7))
cy bo (2, 4)
cy fay (4, 4)
ana fay None

Here are those three pairs on the grid. A k marks each day that can be the first person's last day:

Three pairs. k marks a day that can be the first person's last day
cy, then bo
1234567cyxxxxboxxxxxkkkk
cy, then fay
1234567cyxxxxfayxxxxkk
ana, then fay
1234567anaxxxxxfayxxxxk

cy can hand to bo on any of days 2 to 4, and to fay only after day 4. ana and fay have no day 4 between them, so they fail.

The closed overlap test won't do here, because (begins_b - 1, reach_a) is often empty. For ana then fay it's (4, 3): nobody covers day 4, and the closed test still says it overlaps (1, 6).

Over every ordered pair from the table, the days that work:

FirstSecondHandoff days
anabo2 to 3
anadev1 to 3
cybo2 to 4
cydev1 to 4
cyfay4
faydev1
eliana, bo, dev or fay5 to 6, 2 to 6, 1 to 6, 4 to 6
ana, cy or fayeli1 to 3, 1 to 4, 1

It agreed with the slow day-by-day check on every pair here and on 500 random cases. The last two rows involve eli, who can take the whole week alone. Whether a pair with someone like that counts is a rule of the problem, so read it or ask.

In the editor, handoff_days(a, b, start, end) is the window test above with one bound changed. It lets eli's last day be day 7, which leaves ana no day at all. Fix the window.

On closed days, when neither person covers the range alone, a pair works if begins_b <= reach_a + 1

When neither person covers the range alone, reach_a is at most end - 1 and begins_b - 1 is at least start. Then the window is just (begins_b - 1, reach_a), and the whole test is one comparison: begins_b <= reach_a + 1. The second person has to be back by the day after the first one's run ends.

Building each person's runs is O(d log d) for d free days. Then each pair is O(1), so all pairs cost O(m²) instead of O(m² L²).

Here it is measured over every ordered pair on a 30-day rotation, days 15 through 44. Each engineer, drawn with random.Random(5), is free from day 1 through a random day c from 1 to 60. They're free again from a random day between c and 61 through day 60:

EngineersOrdered pairsPairs that workDay by dayreach_and_begin, then handoff_days
502,45099626.9 ms0.72 ms
1009,9004,160117.2 ms2.67 ms
20039,80017,711475.6 ms9.53 ms

The fast column includes computing every engineer's reach and begins, with the reach_and_begin you wrote.

In the editor, RB holds each person's (reach, begins) for the week from day 1 through day 7. Write working_pairs(rb, end): every ordered pair that splits the range by the one comparison, leaving out anyone who covers it alone.

Part 5 done
Part 6 of 8about 20 min
The best set

Pick the best set of machines that fits a need

Now a different question about the same kind of resources: which set of them fits a need, at the best price?

On these machines, two greedy rules pay more than the cheapest set

A job needs 8 GPUs, and the lab has six machines, each with its GPUs and its cost per hour:

MACHINES = {
    "atlas": {"gpus": 8, "cost": 20},
    "birch": {"gpus": 4, "cost": 9},
    "cedar": {"gpus": 4, "cost": 8},
    "delta": {"gpus": 2, "cost": 3},
    "ember": {"gpus": 2, "cost": 5},
    "fjord": {"gpus": 6, "cost": 15},
}


def gpus(group):
    return sum(MACHINES[name]["gpus"] for name in group)


def cost(group):
    return sum(MACHINES[name]["cost"] for name in group)


for group in [("atlas",), ("delta", "cedar", "birch"), ("cedar", "delta", "ember")]:
    print(group, gpus(group), cost(group))
('atlas',) 8 20
('delta', 'cedar', 'birch') 10 20
('cedar', 'delta', 'ember') 8 16

Two greedy rules come to mind, and both pay too much here:

  • Biggest machine first takes atlas alone, for 20.
  • Most GPUs per unit of cost first takes delta, cedar and birch: 10 GPUs for 20.

The cheapest set that fits is cedar, delta and ember: exactly 8 GPUs for 16. A rule that commits to one machine at a time can be fooled like this. So with a handful of machines, try every set.

In the editor, MACHINES is the lab above. Write by_ratio(machines, need): the most-GPUs-per-cost rule, which takes machines in that order until their GPUs reach need.

combinations visits every set once, and one tuple key ranks them

With only a handful of machines, you can try every set, and Python's itertools lists the sets for you.

from itertools import combinations

names = sorted(MACHINES)
every = [group for size in range(1, len(names) + 1)
         for group in combinations(names, size)]
fits = [group for group in every if gpus(group) >= 8]
print(len(every), len(fits))
for group in every[4:9]:
    print(group)
63 53
('ember',)
('fjord',)
('atlas', 'birch')
('atlas', 'cedar')
('atlas', 'delta')

itertools.combinations(names, size) hands out every set of size names. A loop over sizes from 1 up visits every set once, the small ones first.

Sort the names first and you get two orders for free. Each group lists its names alphabetically, and the groups of one size come out in alphabetical order too. The itertools docs promise both when the input is sorted.

n machines have 2n−12^n - 1 sets that aren't empty: each machine is in or out, which makes 2 to the power n choices, and one of them is the empty set. That's 63 here, and 53 of them have at least 8 GPUs.

To rank the sets, write the order as a tuple. Fewest machines first, then the most GPUs, then the names alphabetically, is the key (len(group), -gpus(group), group). Python compares tuples field by field, and the first field that differs decides.

Predict

Two sets of 2 machines: birch and fjord with 10 GPUs, birch and cedar with 8. Under the key (len, -gpus, names), which sorts first?

Pick an answer above to see the rest

You may stop at the first size that fits only when the fewest machines come first

With fewest machines first, the first size that has any set with 8 GPUs holds the winner. You can stop there: size 1 already has atlas.

With least cost first, you can't. Here is the cheapest set that fits at each size:

SizeCheapest set with 8 GPUsCost
1atlas20
2birch, cedar17
3cedar, delta, ember16
4birch, cedar, delta, ember25

A search that stops at the first size with a fit returns atlas, for 20. The best set has 3 machines and costs 16. A set is ranked by its key, not by when the loop met it.

In the editor, write the loop body of cheapest_set(machines, need): for each set that fits, build its key, the least cost, then the fewest machines, then the names, and keep the smallest in best.

CheckpointEvery set, ranked by one key

Each machine has gpus and an hourly cost. Finish the loop in cheapest_set(machines, need): return the sorted names of the best set whose GPUs add up to at least need, each machine used at most once, or [] if no set does. Best means the least total cost, then the fewest machines, then the alphabetically first list of names. best holds the key of the best set so far.

When the fit is a sum, every member is needed if dropping the smallest breaks the fit

A scheduler that offers choices shouldn't offer atlas plus delta. Atlas alone already fits, so delta is dead weight. A set where every machine is needed is one where dropping any one of them breaks the fit:

def every_one_needed(group, need):
    return all(gpus(group) - MACHINES[name]["gpus"] < need for name in group)


needed = [group for group in fits if every_one_needed(group, 8)]
for group in sorted(needed, key=lambda g: (len(g), -gpus(g), g)):
    print(group, gpus(group))
('atlas',) 8
('birch', 'fjord') 10
('cedar', 'fjord') 10
('birch', 'cedar') 8
('delta', 'fjord') 8
('ember', 'fjord') 8
('birch', 'delta', 'ember') 8
('cedar', 'delta', 'ember') 8

When the fit is a sum, one check does it. Dropping the machine with the fewest GPUs loses the least. So if even that drop breaks the fit, every other drop does too: gpus(group) - min(MACHINES[n]["gpus"] for n in group) < need.

Of the 53 sets with at least 8 GPUs, 8 have every machine needed, and the two checks agreed on all 53. They're printed above in the order of (len(group), -gpus(group), group).

In the editor, sizes holds the GPUs of each machine in a set that fits. Write all_needed(sizes, need): the one check, whether dropping the smallest machine breaks the fit.

Trying every set is O(n 2^n): fine for about 15 items, out of reach for thousands

Each set costs O(n) to add up, so trying every set is O(n 2^n). Here it is timed with your cheapest_set search. The machines are random, with 1 to 8 GPUs each, and the need is twice the number of machines:

MachinesSetsTime to try them all
101,0231.0 ms
1532,76729.9 ms
201,048,5751,193.6 ms

For the 15 or so machines in one rack, or listings in one neighborhood, that's fine, and it's the right first answer.

Every 5 more items multiply the number of sets by 32. Thirty machines have 1,073,741,823 sets. At the rate measured for 20, about 880,000 sets a second, that's about 20 minutes. Thousands are out of reach for any computer.

In the editor, write sets(n), how many sets of n items aren't empty, and minutes(n, per_second), how long trying them all takes at that many sets a second.

For thousands, stop listing sets and build a table instead. It's a dynamic program like the one in the sorting and binary search lesson's worked example.

best[g] is the least cost of a set of the machines seen so far whose GPUs add up to g. Any total at or above need counts as need. Fill the table one machine at a time, and the answer is best[need]:

import math


def least_cost(machines, need):
    # best[g]: least cost for g GPUs, g capped at need
    best = [0] + [math.inf] * need
    for m in machines.values():
        # downward, so each machine is used at most once
        for have in range(need, -1, -1):
            if best[have] < math.inf:
                to = min(need, have + m["gpus"])
                best[to] = min(best[to], best[have] + m["cost"])
    return best[need]


print(least_cost(MACHINES, 8))
Predict

The table keeps the cheapest cost to reach each GPU total. What's the cheapest way to at least 8 GPUs, after every machine?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 6 done
Part 7 of 8about 16 min
The worked example

A worked example: the fewest shifts that cover two weeks

The prompt: engineers offer on-call shifts as closed day ranges, and the rotation runs from day 1 through day 14. Return the fewest shifts that together cover every day, or -1 if they can't. Here are the shifts:

Predict

Shifts (1, 3), (1, 5), (2, 8), (4, 6), (6, 12), (7, 10), (9, 14), (11, 14) and (13, 14) cover days 1 to 14. What's the fewest that cover every day?

Pick an answer above to see the rest

On these shifts, trying every set finds 3, and two greedy rules find more

Now run the search that tries every set against two greedy rules, on the same nine shifts.

from itertools import combinations

SHIFTS = [(1, 3), (1, 5), (2, 8), (4, 6), (6, 12), (7, 10), (9, 14), (11, 14), (13, 14)]


def fewest_by_trying(shifts, start, end):
    days = set(range(start, end + 1))
    for size in range(1, len(shifts) + 1):
        for group in combinations(shifts, size):
            if days <= {d for s, e in group for d in range(s, e + 1)}:
                return size
    return -1


print(fewest_by_trying(SHIFTS, 1, 14))
3

The obvious answer tries every set of shifts, smallest first, and returns the size of the first set that covers. That's O(2^n) sets, each checked in O(n L) for a range of L days. It finds 3.

Then come the greedy rules people reach for. They're worth naming, because both fail here:

  • Longest shift first, skipping any that adds no new day: (2, 8), then (6, 12), then (9, 14), then (1, 5) for day 1. That's 4.
  • In start order, take each shift that extends what's covered: (1, 3), (1, 5), (2, 8), (6, 12), (9, 14). That's 5.

In the editor, write the loop of take_what_extends(shifts, start, end): the second rule, which takes each shift in start order that reaches past covered. On SHIFTS it takes 5.

Among the shifts that start by the first uncovered day, take the one that reaches farthest

Some shift has to cover day 1. Among the shifts that do, take the one that reaches farthest, (1, 5).

Why is that safe? Whatever shift the best answer used for day 1, swap it for (1, 5). Both start by day 1, and (1, 5) ends no earlier. So it covers every day that shift covered from day 1 on. The answer still covers the rotation with the same count, so the swap never hurts.

Now the first uncovered day is 6, and the same argument applies. Among the shifts that start on day 6 or earlier, take the one that reaches farthest. Repeat until day 14 is covered. If no shift that starts by the first uncovered day reaches past what's covered, that day has no shift, and the answer is -1.

def fewest_shifts(shifts, start, end):
    # by start day
    shifts = sorted(shifts)
    # days start..covered are covered
    count, covered, i = 0, start - 1, 0
    while covered < end:
        reach = covered
        # starts by the first uncovered day
        while i < len(shifts) and shifts[i][0] <= covered + 1:
            reach = max(reach, shifts[i][1])
            i += 1
        # nothing covers day covered + 1
        if reach == covered:
            return -1
        count, covered = count + 1, reach
    return count


print(fewest_shifts(SHIFTS, 1, 14))
3

Trace it the way you'd narrate it:

RoundFirst uncovered dayShifts that start by thenFarthest reachCovered through
11(1, 3), (1, 5)55
26(2, 8), (4, 6), (6, 12)1212
313(7, 10), (9, 14), (11, 14), (13, 14)1414

Three shifts, (1, 5), (6, 12) and (9, 14). Here they are with the first uncovered day of each round:

Three rounds, each from the first uncovered day
1613
round 1: (1, 5)
round 2: (6, 12)
round 3: (9, 14)
1613

The lines mark the first uncovered day of each round: 1, 6 and 13.

Each shift is looked at once, because i only moves forward. A shift that started early enough for one round started early enough for every later one. So the next round only needs the shifts after it.

In the editor, chosen(shifts, start, end) is fewest_shifts changed to return the shifts it picks. Write the inner loop, which keeps in best the shift that reaches farthest.

On closed days the test is covered + 1, and covered starts at start - 1

shifts[i][0] <= covered + 1 is the closed-days rule from the handoffs. A shift that starts the day after the covered stretch ends continues it. Two slips break it:

  • Write <= covered, and the first round looks for shifts that start by day 0. It finds none, and returns -1 for a rotation that three shifts cover.
  • Start covered at start instead of start - 1, and day 1 counts as covered before any shift is chosen. That version returned 2.

With half-open hours, where (1, 5) covers up to the instant 5, covered starts at start and the test is <= covered.

In the editor, fewest_blocks(blocks, start, end) is the cover for closed days. Change it for half-open hours, where a block that starts as another ends continues it.

Check it against trying every set, then give the cost

On 3,000 random cases of up to 8 shifts, the greedy matched trying every set each time. Longest first got 129 of them wrong, and taking whatever extends got 364 wrong.

The sort is O(n log n) and the walk is O(n). Here is a measurement on n random shifts, each starting on a random day from 1 to n and lasting 5 to 30 days, plus a shift (1, 30). Covering days 1 through n took 2.93 ms for 10,000 shifts. It took 45.17 ms for 100,000 shifts, and 27.11 ms of that was the sort.

In the editor, write first_mismatch(fast, slow, cases): the twin check that compared each fast version above with a slow one. In the example, abs and lambda x: x stand in for the two, and they first differ on (-2,).

Part 7 done
Part 8 of 8about 23 min
Follow-ups

What interviewers ask next

Bookings that arrive one at a time: bisect finds the only two that can clash

A booking calendar accepts a booking only if it overlaps none already taken. Keep the starts and the ends in two sorted lists:

from bisect import bisect_right


class Calendar:
    def __init__(self):
        self.starts, self.ends = [], []

    def book(self, start, end):
        i = bisect_right(self.starts, start)
        # the one before runs past our start
        if i > 0 and self.ends[i - 1] > start:
            return False
        # the next one starts before we end
        if i < len(self.starts) and self.starts[i] < end:
            return False
        self.starts.insert(i, start)
        self.ends.insert(i, end)
        return True


calendar = Calendar()
tries = [(10, 20), (15, 25), (20, 30), (5, 10), (9, 11), (30, 31), (25, 26)]
print([calendar.book(start, end) for start, end in tries])
[True, False, True, True, False, True, False]

Kept bookings never overlap each other. So a new booking can only clash with its neighbors in start order: the one just before it and the one just after. bisect_right finds its place, and two comparisons decide. Here is the last call, (25, 26), where bisect_right returns 3:

A new booking, (25, 26), between its neighbors
0: (5, 10)
1: (10, 20)
2: (20, 30) i - 1: ends after 25
3: (30, 31) i: starts after 26
new (25, 26)
51015202530

Booking 2 runs past 25, so (25, 26) is refused. The class matched a scan of every kept booking on 300 random runs.

The search is O(log n), and the insert is O(n) because the list shifts. That's the insort cost from the sorting and binary search lesson. For a calendar that also merges, use insert from the merge section. For many writes at scale, a balanced search tree keeps both at O(log n).

In the editor, STARTS and ENDS are the kept bookings from the figure, in start order. Write the rest of clash_with(starts, ends, start, end): the neighbor the new booking overlaps, or None.

The most pay from jobs that can't overlap: sort by end, then take or skip each job

That's the worked example of the sorting and binary search lesson. Sort by end. For each job, take the better of two choices: skip it, or take it plus the best before its start, found with bisect_right.

It's on Airbnb's LeetCode tag lists (4 sources), and one Airbnb software engineer candidate reports it as a phone screen (1 report). Its tie rule is the half-open one: a job can start the hour another ends.

In the editor, each job is (start, end, pay). max_pay(jobs) sorts them by end, and best[j] is the most pay from the first j jobs. Write the loop body: skip the job, or take it plus the best before its start.

A calendar as the bits of one integer: one AND checks a stretch of days

The practice problem's follow-ups ask for a bitmask version. Give each day a bit. 1 << day shifts a 1 left by day places, so 1 << 3 is 8, 0b1000: a number whose only set bit is bit 3. Adding one of those per free day gives one bit per day. (1 << k) - 1 is k ones in a row, and shifting that left by lo moves them onto days lo to hi:

ana_free = sum(1 << day for day in {1, 2, 3, 6, 7})


# one bit for each day lo through hi
def days_mask(lo, hi):
    return ((1 << (hi - lo + 1)) - 1) << lo


print(ana_free, bin(ana_free))
print(days_mask(1, 3), days_mask(1, 4))
print(ana_free & days_mask(1, 3) == days_mask(1, 3))
print(ana_free & days_mask(1, 4) == days_mask(1, 4))
print(ana_free.bit_count())
206 0b11001110
14 30
True
False
5

ana's free days {1, 2, 3, 6, 7} become 0b11001110, which is 206. Days 1 through 3 are the mask 0b1110, 14.

Predict

206 & 14: what does the AND give, and is ana free on days 1 through 3?

Pick an answer above to see the rest

Real dates and time zones: store and compare instants in UTC

For whole days, turn dates into integers with date.toordinal(). Then runs work across a month or a year boundary with the code you already have:

from datetime import date, datetime, timezone
from zoneinfo import ZoneInfo

print(date(2026, 12, 30).toordinal(), date(2027, 1, 2).toordinal())

new_york = ZoneInfo("America/New_York")
midnight = datetime(2026, 11, 1, tzinfo=new_york)
next_midnight = datetime(2026, 11, 2, tzinfo=new_york)
print(next_midnight - midnight)
print(next_midnight.astimezone(timezone.utc) - midnight.astimezone(timezone.utc))
739980 739983
1 day, 0:00:00
1 day, 1:00:00

For times, the trap is daylight saving. When both datetimes carry the same tzinfo object, Python's subtraction ignores the zone, as its docs say. So midnight to midnight on November 1, 2026 in New York comes out as 1 day. Converted to UTC first, the same two instants are 25 hours apart. March 8, 2026, the day the clocks go forward, is 23 hours long.

Overlaps across zones go wrong as well. A 9:00 to 10:00 meeting in New York and a 14:00 to 15:00 meeting in London never overlap as local times.

Predict

New York ends daylight time a week after London. On November 2, do 9:00 to 10:00 in New York and 14:00 to 15:00 in London overlap?

Pick an answer above to see the rest

The fewest stays for a longer trip is the fewest-shifts greedy

No pair covers the range, so find the fewest stays. Every listing's runs within the trip are closed intervals. The fewest stays that cover the trip is fewest_shifts on all of them, and the moves are one fewer than the stays.

The cheapest among the fewest stays is a different question, and the greedy can't answer it. That takes a table over the nights.

In the editor, runs and fewest_shifts are filled in, and TRIP maps each listing to its free nights. Write fewest_moves(listings, start, end): every listing's runs go to fewest_shifts, and the moves are one fewer than the stays.

Many searches against the same calendars: build the runs once, then binary-search them

Build each person's or each listing's runs once, sorted. A search for the run that holds a day is then a binary search on the run starts. bisect_right(starts, day) - 1 gives the last run that starts at or before the day. That run holds the day if its end is at least the day.

Then reach and begins cost O(log r) for r runs, instead of a pass over the days.

In the editor, STARTS and ENDS are ana's runs, (1, 3) and (6, 7). Write run_holding(starts, ends, day): the run that holds day, found with one bisect_right.

The tests you'd write

  • Back to back: (1, 4) and (4, 7) half-open, which must not overlap, and the closed version, (1, 3) and (4, 7), which must join.
  • One interval inside another.
  • Two identical intervals.
  • An empty input and a single interval.
  • A range of one day.
  • A day nobody covers.
  • A twin: the slow version run side by side with the fast one on thousands of small random inputs, as this lesson did for every fast version it shows.

In the editor, overlaps is the right test, and CASES holds one case. Add (a, b, expected) cases to CASES until they catch both broken tests from the start of the lesson: the end test and the closed test.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
6 questions
  1. 1.Two half-open intervals are (s1, e1) and (s2, e2), start in and end out, each with its start before its end. Which test is true exactly when they overlap?

  2. 2.Free time walks busy blocks in start order, (12, 15), (13, 14), (15, 16), in a day from 12 to 17, but sets free_from = end instead of max(free_from, end). What does it report?

  3. 3.Half-open reservations (1, 4), (4, 7) and (7, 9) go through a sweep that sorts its events so that, at one time, starts come before ends. How many machines does it say are needed?

  4. 4.A rotation runs from day 1 through day 7, closed. Engineer A is free days 1 through 4, and engineer B days 5 through 7. Can A hand off to B?

  5. 5.You want the set of machines with enough GPUs that costs the least, then has the fewest machines. You try sets smallest first with combinations. Can you stop after the first size that has a set that fits?

  6. 6.Shifts are closed day ranges, and you need the fewest that cover days 1 through 14. Which choice, repeated, always gives the fewest?

Practice

Sources (7)
  1. Why numbering should start at zero (EWD 831) · E.W. Dijkstra Archive, University of Texas at Austin · Aug 11, 1982
    “in either convention two subsequences are adjacent means that the upper bound of the one equals the lower bound of the other”
  2. Built-in Types: Ranges · Python 3.12 documentation · Oct 26, 2026
    “For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.”
  3. Expressions: Value comparisons · Python 3.12 documentation · Oct 26, 2026
    “Collections that support order comparison are ordered the same as their first unequal elements”
  4. itertools: combinations · Python 3.12 documentation · Oct 26, 2026
    “The combination tuples are emitted in lexicographic order according to the order of the input iterable. If the input iterable is sorted, the output tuples will be produced in sorted order.”
  5. Built-in Types: int.bit_count · Python 3.12 documentation · Oct 26, 2026
    “Return the number of ones in the binary representation of the absolute value of the integer.”
  6. datetime: datetime objects, supported operations · Python 3.12 documentation · Oct 26, 2026
    “If both are naive, or both are aware and have the same tzinfo attribute, the tzinfo attributes are ignored”
  7. zoneinfo: IANA time zone support · Python 3.12 documentation · Oct 26, 2026
    “The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615.”