Algorithms · Visualized
Activity Selection
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
Given activities each with a start and end time, select the maximum number of non-overlapping activities that can be performed by a single person. Time: O(n log n) average, O(n log n) worst; space: O(1) extra, or O(n) if sorting isn't in place.
Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.
Activity Selection
GreedyGiven activities each with a start and end time, select the maximum number of non-overlapping activities that can be performed by a single person. The greedy insight: always sort by end time and pick the activity that finishes earliest among the remaining valid options — finishing early leaves the most room for future activities.
How Activity Selection Works
- Sort all activities by their end time in ascending order.
- Select the first activity (it has the earliest finish time), and remember its end time.
- Go through the remaining activities in sorted order.
- If an activity's start time is at or after the last selected activity's end time, select it and update the 'last end time'.
- Continue through the whole list — the collected selections are the maximum non-overlapping set.
Activity Selection Worked Example
Input: [[1, 4], [3, 5], [0, 6], [5, 7], [3, 9], [5, 9], [6, 10], [8, 11], [8, 12], [2, 14], [12, 16]]
Sorted by end time: [1,4],[3,5],[0,6],[5,7],[8,11],[8,12],[12,16]... Pick [1,4] (end=4). Next activity starting ≥4: [3,5] starts at 3, skip. [5,7] starts at 5≥4 → pick (end=7). Next: [8,11] starts at 8≥7 → pick (end=11). Next: [12,16] starts at 12≥11 → pick. Selected: [1,4],[5,7],[8,11],[12,16] — 4 activities.
def activity_selection(start, finish):
n = len(start)
acts = sorted(range(n), key=lambda i: finish[i])
out = [acts[0]]
last = finish[acts[0]]
for i in acts[1:]:
if start[i] >= last:
out.append(i)
last = finish[i]
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Activity Selection Time & Space Complexity
When to Use Activity Selection
- Meeting room / resource scheduling: fitting the maximum number of non-conflicting bookings.
- Classic proof-of-concept for the greedy 'earliest finish time' strategy.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.