Skip to content
StackDecode
GreedyAnimated

Activity Selection

Sort by finish time; take each activity that starts after the last one ends.

Time

O(n log n)

Extra space

O(1)

Use it for

Most non-overlapping events.

How it works

  1. Sort the activities by finishing time.
  2. Take the first one. It finishes earliest, so it blocks the least.
  3. Walk down the list: take an activity only if it starts at or after the end of the last one taken.
  4. Greedy is optimal here: an exchange argument shows some best schedule always starts with the earliest finisher. O(n log n).

Watch it run

Loading animation…