Greedy

Problem shape

Intermediate
4
8
15
16
23
42
Core idea

Sort by ending time and always take the compatible activity that finishes earliest.

Step 1 / 5
Problem shape
Current lesson

Activity Selection Lab

Greedy Intermediate

Activity Selection

Welcome to the Activity Selection algorithm lab. Sort by ending time and always take the compatible activity that finishes earliest. Use it when: Use for maximum number of non-overlapping intervals. The time complexity is O(n log n), and the space complexity is O(1). The pseudocode is: sort intervals by end lastEnd = -infinity for interval in intervals if interval.start >= lastEnd take interval lastEnd = interval.end As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(n log n)

Space

O(1)

Pseudocode

sort intervals by end
lastEnd = -infinity
for interval in intervals
  if interval.start >= lastEnd
    take interval
    lastEnd = interval.end
Open deeper structure lesson
1.0x