Activity selection
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Activity selection picks the largest number of events that do not overlap, from a list of start and end times. The trick is to always take the one that finishes earliest, which leaves the most room for the rest.
Practical use cases
- Web app: Booking the seminar hall. A college portal has 40 booking requests for one hall, each with a start and end time. Sorting by end time and accepting every request that begins after the last accepted ended gives the most events in the hall, with no manual juggling.
- Web app: Cinema screen programming. A theatre admin tool has show slots requested by distributors for a single screen. Picking by earliest finish schedules the greatest number of shows in a day. Distributors see their slots confirmed instantly, and the cinema fits more shows into the day, which means more tickets sold.
- Web app: Doctor appointment slots. A clinic app has requests of different lengths for one doctor. Choosing by earliest end time fits the most patients into the afternoon. Fewer patients are left unseen at the end of the day.
- System: Job runners and batch machines. A batch machine that can run one job at a time uses this to complete the most jobs in a time window.
The story: The Busy School Hall
Mrs. Sharma was in charge of the school hall for Annual Day Week. Eleven clubs wanted it: dance, drama, quiz, robotics, rangoli, and more. Every club gave a start and end hour, and the hall could host only one club at a time.
"I want as many clubs as possible to perform," she said. Aarav suggested picking the club that starts first. But the Drama club started at hour 0 and ran until hour 6, blocking five little clubs. Zoya suggested picking the shortest club, but a short club in the middle of the day can also split the hall into two useless gaps.
Mira had a different thought: "Which club gives the hall back the soonest? The one that finishes earliest!" Every time the hall is freed early, more time is left for others. Sort by finish time, take the first club, and then walk down the list taking any club that starts after the last one ended.
It worked beautifully: four clubs fit, and nothing else could do better. That clever rule is activity selection, one of the classic greedy wins. Swapping any chosen club for one that finishes later could only hurt, and that is why the greedy choice is safe.
How to spot this problem, and where you need it
You have a single resource, like a room, machine or person, and many requests with start and end times, and you want to serve as many requests as possible without overlaps.
Signs you need it
- The wording is "maximum number of non-overlapping events, meetings or jobs".
- Each request has a start and finish time and only one can use the resource at a time.
- Choosing the longest or the earliest-starting request gives surprisingly poor results.
Where to use it in a project
- Hall, room, lab and equipment booking approval screens.
- Batch job or appointment systems where you must decide which requests to accept.
The solution
Sort the activities by their end time. Accept the first one. Then go through the rest: if an activity starts at or after the end of the last accepted one, accept it; otherwise skip it. Finishing earliest leaves the most free time for what follows, and this choice can be shown never to hurt, so the count of accepted activities is the maximum.
Payoff: Before: manually approving 12 of 40 requests. After: one sort and pass approves 19, the true maximum.
Explain it like I am 8
You have one swing in the park and many kids who want turns. To give turns to the most kids, always let in the kid who will finish soonest. The swing gets free early, so more kids get a go!
How it works, step by step
- Sort all activities by their finish time.
- Pick the first one and remember its finish time as
lastEnd. - Walk through the rest. If an activity starts at or after
lastEnd, pick it and updatelastEnd. - Otherwise it overlaps, so skip it.
- When the list ends, the picked activities are the biggest possible set.
The code in four languages
PHP
<?php
// Each activity is [start, end]. Returns the biggest set that never overlaps.
function selectActivities(array $acts): array {
usort($acts, fn($a, $b) => $a[1] <=> $b[1]); // earliest finish first
$chosen = [];
$lastEnd = 0; // hall is free from hour 0
foreach ($acts as $a) {
if ($a[0] >= $lastEnd) { // starts after the last one ended
$chosen[] = $a;
$lastEnd = $a[1];
}
}
return $chosen;
}
$acts = [[1,4],[3,5],[0,6],[5,7],[3,9],[5,9],[6,10],[8,11],[8,12],[2,14],[12,16]];
$picked = selectActivities($acts);
echo count($picked) . " activities: " . json_encode($picked) . PHP_EOL;JavaScript
// Each activity is [start, end]. Returns the biggest set that never overlaps.
function selectActivities(acts) {
acts = [...acts].sort((a, b) => a[1] - b[1]); // earliest finish first
const chosen = [];
let lastEnd = 0; // hall is free from hour 0
for (const a of acts) {
if (a[0] >= lastEnd) { // starts after the last one ended
chosen.push(a);
lastEnd = a[1];
}
}
return chosen;
}
const acts = [[1,4],[3,5],[0,6],[5,7],[3,9],[5,9],[6,10],[8,11],[8,12],[2,14],[12,16]];
const picked = selectActivities(acts);
console.log(picked.length + " activities: " + JSON.stringify(picked));Java
import java.util.*;
public class Main {
// Each activity is {start, end}. Returns the biggest set that never overlaps.
static List<int[]> selectActivities(int[][] acts) {
int[][] sorted = acts.clone();
Arrays.sort(sorted, (a, b) -> Integer.compare(a[1], b[1])); // earliest finish first
List<int[]> chosen = new ArrayList<>();
int lastEnd = 0; // hall is free from hour 0
for (int[] a : sorted) {
if (a[0] >= lastEnd) { // starts after the last one ended
chosen.add(a);
lastEnd = a[1];
}
}
return chosen;
}
public static void main(String[] args) {
int[][] acts = {{1, 4}, {3, 5}, {0, 6}, {5, 7}, {3, 9}, {5, 9}, {6, 10}, {8, 11}, {8, 12}, {2, 14}, {12, 16}};
List<int[]> picked = selectActivities(acts);
System.out.println(picked.size() + " activities: " + Arrays.deepToString(picked.toArray()));
}
}Go
package main
import (
"cmp"
"fmt"
"slices"
)
// selectActivities takes activities as [start, end] and returns the biggest set that never overlaps.
func selectActivities(acts [][2]int) [][2]int {
sorted := slices.Clone(acts)
slices.SortFunc(sorted, func(a, b [2]int) int { return cmp.Compare(a[1], b[1]) }) // earliest finish first
var chosen [][2]int
lastEnd := 0 // hall is free from hour 0
for _, a := range sorted {
if a[0] >= lastEnd { // starts after the last one ended
chosen = append(chosen, a)
lastEnd = a[1]
}
}
return chosen
}
func main() {
acts := [][2]int{{1, 4}, {3, 5}, {0, 6}, {5, 7}, {3, 9}, {5, 9}, {6, 10}, {8, 11}, {8, 12}, {2, 14}, {12, 16}}
picked := selectActivities(acts)
fmt.Println(len(picked), "activities:", picked)
}Time: O(n log n) · Extra space: O(n). Sorting is the expensive part; the single walk after it is just O(n).
Watch out for
- Sorting by start time or by length. Only "earliest finish" is proven safe here.
- Using
>instead of>=so activities that just touch (end 4, start 4) wrongly count as overlapping. - Forgetting to update
lastEndafter picking an activity.
Quick check
- Which sort order makes activity selection correct?
- By start time
- By finish time
- By length
- An activity starts exactly when the last chosen one ends. What do we do?
- Skip it
- Take it only if it is short
- Take it
- What is the time complexity?
- O(n log n)
- O(n)
- O(n²)