Activity selection
how it works
The idea on the watch page's first example, four activities and one room. Then the whole method on it, step by step.
A runs from 0 to 6, B from 1 to 2, C from 3 to 4 and D from 5 to 7. The room holds one at a time. Two activities clash when each starts before the other ends. Two that only touch, one ending as the next starts, do not clash. Earliest start first takes A. A runs till 6 and clashes with B, C and D: 1 activity. Earliest finish first takes B, then C, then D: 3, the most, as section 4's question 4 shows. So line the activities up by the hour each ends, earliest first: B, C, A, D. Take each in turn. Choose it if it starts once the last one chosen has ended, and rule it out if not. The table below walks it. Lining them up is a sort, and the watch page's sort is merge sort. It merges the ends, typed 6, 2, 4, 7, in pairs. 6 with 2 takes 1 comparison, 4 with 7 takes 1, then 2, 6 with 4, 7 takes 3: 2 against 4, 6 against 4, 6 against 7. That is 5 comparisons. Then each activity after the first is checked once against the room's free hour: 3 checks. This page counts the comparisons, the dearer part. The code below lines them up with Python's own sort and returns the activities chosen.
| in order | hours | free from | does |
|---|---|---|---|
| B | 1 to 2 | - | choose |
| C | 3 to 4 | 2 | choose |
| A | 0 to 6 | 4 | rule out |
| D | 5 to 7 | 4 | choose |
step 1 of 6
Line the 4 activities up by the hour each ends, earliest first: B, C, A and D.
what it remembers to know where it is
- room free from
- not yet
Where it says not yet, nothing is held there at that moment.
step 2 of 6
B runs from 1 to 2 and ends earliest. Nothing is chosen yet, so choose B. The room is free again from 2.
what it remembers to know where it is
- room free from
- 2
step 3 of 6
C runs from 3 to 4. The last one chosen, B, ends at 2, so C fits after it. Choose C.
what it remembers to know where it is
- room free from
- 4
step 4 of 6
A runs from 0 to 6, but starts before C, the last one chosen, ends at 4, so they clash. Rule A out.
what it remembers to know where it is
- room free from
- 4
step 5 of 6
D runs from 5 to 7. The last one chosen, C, ends at 4, so D fits after it. Choose D.
what it remembers to know where it is
- room free from
- 7
step 6 of 6
Done: B, C and D fit, 3 activities with no two at once, the most there can be.
what it remembers to know where it is
- room free from
- 7
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- line the activities up by the hour each ends, earliest firstPython lines 9 and 10
- take each in that orderPython line 11
- it starts once the last one chosen has ended, or nothing is chosen yet, so choose itPython lines 14 and 15
- otherwise it clashes with the last one chosen: rule it outPython lines 12 and 13
- the activities chosen are as many as fitPython line 16
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def activity_selection(activities):
"""Fit the most activities into one room, no two at once.
activities is a list of (start, end) pairs of whole hours, each ending
after it starts. Returns the activities chosen, in the order chosen.
"""
chosen = []
free = None # the hour the room is free again from; nothing chosen yet
# line them up by the hour each ends, earliest first; equal ends by start
in_order = sorted(activities, key=lambda a: (a[1], a[0]))
for start, end in in_order: # take each in that order
if free is not None and start < free: # it starts before the last one chosen ends
continue # so they clash: rule it out
chosen.append((start, end)) # choose it
free = end # the room is free again from its end
return chosen # as many as fit
how it scales
The plot counts the sort's comparisons on activities, each an hour long, back to back, in two orders. Latest end first is the fewest any order costs, and the dearest order the most. Measured from 10 to 100,000.
Each mark across or up is ten times the one before. Both lines climb a little over one mark up for each mark across. The dearest order makes 589 at 100 activities and 8,985 at 1,000, about 15 times. The plot's note reads it further out, from a million to ten million activities: about 12 times. The extra over ten times comes from the log in , which section 4 derives.
comparisons to line them up, ten times more at each mark up
, how many activities there are, ten times more at each mark to the right
- the dearest order, each an hour longsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, 12 times the work
- latest end first, each an hour longsolid where measured by running it; dashed where its formula carries it on to ten million
| comparisons to line them up | time | |
|---|---|---|
| 1,000 | 8,985 | about 9 microseconds |
| 100,000 | 1,592,993 | about 1.6 milliseconds |
| 10,000,000 | 226,648,193 | about 227 milliseconds |
The comparisons to line them up are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count activity selection's comparisons yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it lines up n activities,
each an hour long, back to back, in two orders: latest end first, the fewest
comparisons any order costs, and the dearest order, the most. It prints the
comparisons the sort makes for each, by count below, the watch page's merge
in place of Python's own sorted. The counts are the same on any computer;
only the time differs.
"""
def activity_selection(activities):
"""Fit the most activities into one room, no two at once.
activities is a list of (start, end) pairs of whole hours, each ending
after it starts. Returns the activities chosen, in the order chosen.
"""
chosen = []
free = None # the hour the room is free again from; nothing chosen yet
# line them up by the hour each ends, earliest first; equal ends by start
in_order = sorted(activities, key=lambda a: (a[1], a[0]))
for start, end in in_order: # take each in that order
if free is not None and start < free: # it starts before the last one chosen ends
continue # so they clash: rule it out
chosen.append((start, end)) # choose it
free = end # the room is free again from its end
return chosen # as many as fit
def count(activities):
"""How many comparisons the watch page's sort makes: runs of 1, 2, 4
and on, merged in neighbouring pairs, comparing their front activities
by end, and by start when two end at the same hour."""
runs = [[(end, start)] for start, end in activities]
compared = 0
while len(runs) > 1:
merged = []
for k in range(0, len(runs) - 1, 2):
left, right = runs[k], runs[k + 1]
run = []
i = j = 0
while i < len(left) and j < len(right):
compared += 1
if right[j] < left[i]:
run.append(right[j])
j += 1
else:
run.append(left[i])
i += 1
merged.append(run + left[i:] + right[j:])
if len(runs) % 2 == 1:
merged.append(runs[-1])
runs = merged
return compared
def cheapest(n):
"""n activities an hour long, back to back, typed latest end first."""
return [(n - 1 - k, n - k) for k in range(n)]
def dearest(n):
"""n activities an hour long, back to back, their ends in the dearest
order: in every merge, the two latest ends sit in different runs."""
order = [0] * n
def deal(at, ends):
if len(ends) == 1:
order[at] = ends[0]
return
split = 1
while split * 2 < len(ends): # the largest power of 2 below the run's length
split *= 2
left, right = [], []
for i, end in enumerate(reversed(ends)): # from the latest end down
if i % 2 == 0 and len(right) < len(ends) - split:
right.insert(0, end)
else:
left.insert(0, end)
deal(at, left)
deal(at + split, right)
deal(0, list(range(1, n + 1)))
return [(end - 1, end) for end in order]
if __name__ == "__main__":
print(f"{'n':>7} {'latest end first':>17} {'dearest':>10}")
for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
print(f"{n:>7} {count(cheapest(n)):>17} {count(dearest(n)):>10}")
best, worst and average
Here best and worst are orders: the same activities, typed in a different order. Which runs the sort merges depends only on ; where each merge stops, when one run is used up, depends on the order typed. So the order alone moves the comparisons. The checks never move: on every list. No average is worked out.
A case is one order of the activities. A bound says how fast that order's cost grows as activities are added.
The counts are in the grid below. A count is often made of pieces that grow at different speeds, and the fastest-growing piece swamps the rest. In the dearest order at 1,000 activities, is 10,000, less 16 waiting and 999 for the merges: 8,985. The 10,000 is most of it. So how a cost grows is what tells one method from another, and the bounds keep just that.
| bestlatest end first, each an hour long | worstthe dearest order, each an hour long | |
|---|---|---|
| comparisons to line them up | , the right runs | |
| activities checked | ||
| how the comparisons to line them up grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: A second list of the activities for the sort, and the activities chosen.
Extra memory is the room it needs on top of the input itself, while it runs.
| typed | ends | comparisons | checks |
|---|---|---|---|
| latest end first | 5, 4, 3, 2, 1 | 5 | 4 |
| in end order | 1, 2, 3, 4, 5 | 8 | 4 |
| the dearest order | 1, 3, 2, 4, 5 | 9 | 4 |
where the formula comes from
Questions 1 and 2 count the comparisons, the plot's two lines. Question 3 counts the checks, and question 4 shows why the activities chosen are the most.
the move: how the sort goes
the line:5 numbers stand for 5 activities' ends, latest first. Round 2's merge, 4, 5 with 2, 3, compares 2 with 4, then 3 with 4. Then the right run is used up, and 4 and 5 follow with no comparison. round run length merges comparisons 1 1 2 2 2 2 1 2 3 4 1 1 all 4 5 Five activities, latest end first. In rounds 1 and 2 the last run waits. why it is allowed: The watch page's sort is merge sort, from the bottom up. Each activity starts as a run of 1. Each round merges neighbouring runs, comparing their front activities and taking the one that ends first. A last run with no partner waits. Every run is 1, 2, 4 and on long, except perhaps a round's last, so a right run is never the longer. Which runs meet depends only on , never on the order.
the move: a merge's least
the line:why it is allowed: A merge stops when one run is used up, and each activity of that run needed one comparison to leave it. By line 1, the right run is never the longer. So whichever run is used up holds at least the right run's length. For 4, 5 with 2, 3, at least 2 comparisons.
guess it, thenthe move: latest end first, the right run is used up first
the line:run length right runs comparisons 1 5 of 1 5 2 2 of 2 4 4 1 of 4 4 8 1 of 2 2 all 15 Ten activities, latest end first. At run length 2 the last run waits, and at 4 the last 2 activities wait. At 8 the right run holds only those 2. why it is allowed: Latest end first, each right run's activities end before the left run's beside it. So the right run is used up first, one comparison each, the least line 2 allows. adds up the right runs in the round of runs of 1, of runs of 2, and so on. For 5, 2 + 2 + 1.
guess it, thenthe move: a ceiling
the line:Top, numbers, each double the last; bottom, their logs, each 1 more. 5 lies between 4 and 8, so its log, about 2.3, rounds up to 3. 10 lies between 8 and 16, so its log, about 3.3, rounds up to 4. why it is allowed: In a pair the right run is never the longer, so a round's right runs hold at most half the activities, . Run lengths double until one run holds all , so there are rounds. Multiply the two. For 5, half of 5 times 3 rounds is 7.5, and is 5.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: Rounding up adds less than 1, and from 2 up 1 is at most . So is at most twice , and times twice is . For 5, is 5, at most 11.6.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:run length full pairs hold their right runs a quarter of 5 1 4 2 1.25 2 4 2 1.25 Five activities. In each round with a full pair, the full pairs hold 4 of the 5, at least half, and their right runs 2, at least a quarter. 2 such rounds, so at least 2.5. why it is allowed: Take a round whose runs are long, with at most , so at least one full pair of runs fits. What is left over is shorter than a pair, so the full pairs hold at least half the activities, and their right runs at least a quarter, . Such rounds have as 1, 2, 4 and on, while is at most , so there are of them. By line 3, adds up every round's right runs, so multiply the two. For 5, rounds of 1 and 2, so at least 2.5.
guess it, thenthe move: the rounded log against the exact one
the line:why it is allowed: Call line 7's rounded-down log . Rounding down took off less than 1, so is below . From 2 up is at least 1, so is at most . For 5, is 2, and the log of 5, about 2.3, is below 3, at most 4.
guess it, thenthe move: drop the rounding
the line:why it is allowed: By line 8, is at least half of . Put that into line 7. For 5, is 5, at least 1.45.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 9, with the fixed multiple an eighth.
guess it, thenthe move: both together
the line:why it is allowed: Lines 6 and 10 bound by the same growth.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: a merge's most
the line:why it is allowed: Each comparison sends one activity into the new run. When one run is used up, the other still holds at least one activity, which follows with no comparison.
the move: the dearest order
the line:run of ends left run gets right run gets 1, 2, 3, 4, 5 1, 2, 3, 4 5 1, 2, 3, 4 1, 3 2, 4 1, 3 1 3 2, 4 2 4 Dealing 5 ends. 5 goes right, and a right run of 1 is full, so 1 to 4 go left. Then 4 goes right, 3 left, 2 right and 1 left. Each left run is typed before its right run, so the order is 1, 3, 2, 4, 5. why it is allowed: By question 1's line 1, a run of activities is merged from two runs. The left run holds the largest power of 2 below , and the right run the rest. Deal its ends out from the latest down, one to the right run and one to the left in turn, until the right run is full. The rest go left. Then deal each run the same way. The run without the latest end holds the second latest, its own last, and is used up when that goes in. So only the latest is left, and the merge makes the of line 1.
guess it, thenthe move: each merge, one less than it holds
the line:merge merged comparisons 1 with 3 2 1 2 with 4 2 1 1, 3 with 2, 4 4 3 1, 2, 3, 4 with 5 5 4 all 13 9 The dearest order of 5 ends: 1, 3, 2, 4, 5. The watch page's second example has its ends in this order. 13 merged, 4 merges, 9 comparisons. why it is allowed: By line 2, each merge compares one less than it holds. Add that up over every merge.
guess it, thenthe move: the activities merged
the line:why it is allowed: Each of the rounds, as in question 1's line 4, merges every activity except a run that waits. adds up the activities that wait. For 5, 15 less 2, which is 13.
guess it, thenthe move: the merges
the line:why it is allowed: Each merge makes one run fewer, from runs to 1. For 5, 4.
guess it, thenthe move: put them together
the line:why it is allowed: Lines 3, 4 and 5 together. For 5, 13 less 4, which is 9.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 6, dropping the and the it takes away, as neither is below 0. For 5, 9 is at most 15.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: As in question 1's line 5, is at most twice . For 5, at most 23.2.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 8, with the fixed multiple 2.
guess it, thenthe move: a floor
the line:why it is allowed: By question 1's line 2, every merge compares at least its right run, in any order. So is at least question 1's , and question 1's line 7 gives this floor. For 5, 9 is at least 2.5.
guess it, thenthe move: drop the rounding
the line:why it is allowed: As in question 1's lines 8 and 9. For 5, at least 1.45.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 11, with the fixed multiple an eighth.
guess it, thenthe move: both together
the line:why it is allowed: Lines 9 and 12 bound by the same growth.
guess it, then
try it with a small : at , line 6 gives , which you can work out by hand
the move: one check each, after the first
the line:in order hours free from checks so far does A 0 to 3 - 0 choose C 3 to 5 3 1 choose B 2 to 7 5 2 rule out D 5 to 8 5 3 choose E 6 to 9 8 4 rule out Section 5's five activities, in order of ends. A is chosen with no check. Each of the other 4 is checked once, chosen or ruled out. why it is allowed: The first activity in order is chosen with no check, as nothing is chosen yet. Each other is checked once, against the hour the room is free from. In any order. For 5, 4.
the move: a ceiling
the line:why it is allowed: By line 1, as is less than .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 2, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:why it is allowed: From 2 up, 1 is at most half of , so is at least half of . For 5, 4 is at least 2.5.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple a half.
guess it, thenthe move: both together
the line:why it is allowed: Lines 3 and 5 bound by the same growth.
guess it, thenthe move: the sort grows faster
the line:why it is allowed: By question 1's lines 2, 3 and 9, any order makes at least comparisons, and by line 2 the checks are at most . So the comparisons are at least times the checks, a number that grows without end. It is 1 or more from 256 on, as the log of 256 is 8. At 1,000 activities, 999 checks against 4,932 to 8,985 comparisons. At 100,000, 99,999 against 815,024 to 1,592,993.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: one out, one in
the line:Five activities, hours 0 to 9 below. A best list, A, C and E. Swap 1 puts B, the method's first, in for A. Swap 2 puts D, its second, in for C. No swap makes a clash. why it is allowed: The plan is to turn a best list into this method's list, one swap at a time, never losing an activity. In the picture, A goes out and B comes in. The page on greedy choices proves this under line 2, on five jobs of its own. It calls activities jobs, a list with no clash a day, and this method earliest finish.
the move: add them up
the line:where does this come from?
question 1 of the page greedy choices, and when they failA best day holds jobs. Swap its job that ends first for earliest finish's first job. How many jobs, , does it hold now, and does any clash? the move: one out, one in
the line:A best day of the jobs at the top, C and E. Swap 1 puts B, earliest finish's first job, in for C. Swap 2 puts D, its second, in for E. No swap makes a clash. why it is allowed: The plan is to turn a best day into earliest finish's day, one swap at a time, never losing a job. One job goes out and one comes in. On the day at the top, C goes out and B comes in.
the move: add them up
the line:why it is allowed: One out and one in leaves . B and E are 2 jobs, as C and E were.
the move: nothing clashes
the line:Swap 1, B in for C. B and E fit. why it is allowed: B ends at 2, before C ends at 3. E starts at 3, so no earlier than B ends, and B and E fit. In general, the job put in ends first of all, so no later than the job taken out. Every other job of the best day ends no earlier than the one taken out, so it cannot sit wholly before it. As they do not clash, it starts no earlier than that job ends, so no earlier than the new one ends.
the move: swap again
the line:Swap 2, D in for E. B and D fit. why it is allowed: Both days now start with B, and only jobs starting at 2 or later can sit beside it. Each time, earliest finish takes the job ending first of those starting no earlier than its last job ends. Here that is D, ending at 4. E, the best day's second job, starts at 3, so it is one of them, and ends at 5. So D ends no later than E. D fits beside B, as it starts no earlier than B ends. Any later job of the best day starts no earlier than E ends, as in line 3, so no earlier than D ends. Each next job swaps the same way.
the move: none left over
the line:why it is allowed: Earliest finish's jobs are a day too, so a best day holds at least as many, and the swaps never run out. Swap until every job of earliest finish is in. Any job left over in the best day ends no earlier than the last one swapped in, so, as in line 3, it starts no earlier than that job ends. Then earliest finish would have taken it too. So the best day has no more. At the top, after the swaps the day is B and D, and no job starts at 4 or later.
why it is allowed: One out and one in leaves .
guess it, thenthe move: nothing clashes
the line:why it is allowed: By line 3 of the proof under line 2, the activity put in ends first of all, so the rest of the best list still fits after it. In line 1's picture, B ends at 2, before A ends at 3, so C, starting at 3, still fits.
guess it, thenthe move: none left over
the line:why it is allowed: The method's list has no clash either, so a best list holds at least as many, and the swaps never run out. By lines 4 and 5 of the proof, an activity left over would start once the last one swapped in ends. Then the method would have chosen it too, yet it is not in the method's list. So none is left over, and the method's list is a best list. Here B, D and E, 3.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
count it yourself
Five activities: A from 0 to 3, B from 2 to 7, C from 3 to 5, D from 5 to 8 and E from 6 to 9. Their ends, 3, 7, 5, 8, 9, come in the dearest order, the pattern of 1, 3, 2, 4, 5. The sort makes all 9 comparisons before step 1, so they show together there. Then each activity after the first is checked once. The last columns are running totals.
| step | what happens | comparisons to line them up | activities checked |
|---|---|---|---|
| 1 | Line the 5 activities up by the hour each ends, earliest first: A, C, B, D and E. | 9 | 0 |
| 2 | A runs from 0 to 3 and ends earliest. Nothing is chosen yet, so choose A. The room is free again from 3. | 9 | 0 |
| 3 | C runs from 3 to 5. The last one chosen, A, ends at 3, so C fits after it. Choose C. | 9 | 1 |
| 4 | B runs from 2 to 7, but starts before C, the last one chosen, ends at 5, so they clash. Rule B out. | 9 | 2 |
| 5 | D runs from 5 to 8. The last one chosen, C, ends at 5, so D fits after it. Choose D. | 9 | 3 |
| 6 | E runs from 6 to 9, but starts before D, the last one chosen, ends at 8, so they clash. Rule E out. | 9 | 4 |
| 7 | Done: A, C and D fit, 3 activities with no two at once, the most there can be. | 9 | 4 |
In all, 9 comparisons to line them up. The formula from section 4, , gives at : the same.
where you meet it
The books' courier fills a day this way. Drawn as points joined by lines, the problem has fast methods of its own. Textbooks start their chapters on greedy methods with it.
The courier's day
The books give a courier eight delivery jobs, each in a fixed window, each paying the same. Earliest finish first takes six. Earliest start first takes four. Checking all 256 sets of the eight finds no seven that fit.
source: the books' volume three, chapter 30
Graphs of activities
Draw each activity as a point, and join two points when the activities clash. The most that fit is then the largest set of points with no two joined. In 1972, Fănică Gavril gave fast methods for this on chordal graphs, a family of such drawings that holds every one made from activities.
source: F. Gavril, SIAM Journal on Computing 1(2), 1972, pages 180 to 187, Algorithms for minimum coloring, maximum clique, minimum covering by cliques, and maximum independent set of a chordal graph (opens in a new tab)
Where textbooks start
Kleinberg and Tardos's textbook opens its chapter on greedy methods with this problem, calling it interval scheduling. It proves earliest finish first right by showing the method never falls behind a best list. Cormen and others' textbook opens its greedy chapter with it too, as activity selection.
source: J. Kleinberg and É. Tardos, Algorithm Design, Addison-Wesley, 2006, section 4.1, and T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, 3rd edition, MIT Press, 2009, section 16.1
what is used instead
When activities pay different amounts, earliest finish first can lose. A table of the best pay for the first few activities, filled one at a time, finds the most pay (Kleinberg and Tardos, sections 6.1 and 6.2). With several rooms and every activity to place, take them by start and open a new room only when every room is busy (section 4.1).
how it compares
Other rules look as sensible, and each loses on some list. Trying every set of activities always finds the most, but each activity added doubles the sets: 10 activities have 1,024.
| rule | takes next | always the most |
|---|---|---|
| earliest finish first | the one ending first that fits | yes |
| earliest start first | the one starting first that fits | no: 1 for 3 in section 1 |
| shortest first | the shortest that fits | no: 1 for 2 below |
| every set | tries every set | yes |
| n | earliest finish first: comparisons and checks | every set: sets |
|---|---|---|
| 10 | 36 | 1,024 |
| 20 | 92 | 1,048,576 |
| 40 | 224 | 1,099,511,627,776 |