Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Greedy

Finish First, Fit the Most.

Don't memorize activity selection — watch the greedy choice pay off. You have intervals fighting for one resource — one meeting room, one CPU — and you want to fit the most that don't overlap. The rule is almost too simple: sort by earliest finish time, then take each interval that starts after the last one you took ends. Finishing soonest leaves the most room for everything else, which is exactly why this beats sorting by shortest or by earliest start.

one resource · sort by finish · take if start ≥ last finish · provably optimal
ACTIVITY SELECTION

Pick the most non-overlapping intervals that can share a single resource.

SORT BY FINISH

Order the intervals by earliest end time — the whole trick lives here.

TAKE IF FREE

Take an interval only if its start is ≥ the finish of the last one you took.

WHY IT WORKS

Ending soonest frees the resource earliest, leaving maximum room for the rest.

schedule.sim — 6 intervals, one room
Ready

Six intervals, already sorted by finish time (top = earliest end). Take the first, then scan down: keep any whose start is at or after the last finish, skip the rest. Press Step.

take interval if start ≥ lastEnd; then lastEnd = its end
0
Chosen
—
Last finish

The earliest finish is always safe

Greedy algorithms usually need a proof that the locally best move does not doom you later. Here the move is: among all intervals, commit to the one that finishes first. The argument is an exchange. Take any optimal schedule and look at its first interval by finish time. If it is not the globally earliest-finishing interval, swap it out for that one — the replacement ends no later, so it cannot overlap anything the optimal schedule kept afterward, and the count is unchanged. So there is always an optimal schedule that starts with the earliest-finishing interval. Remove it and everything it overlaps, and the same argument applies to what remains. That is why the simple scan — sort by finish, take when the start clears the last finish — produces a maximum set every time. Sorting by shortest length or earliest start has no such guarantee.

01

Sort by finish time

Order all intervals by their end time, earliest first. This is the O(n log n) step.

02

Track the last finish

Keep lastEnd, the finish of the most recently chosen interval, starting at −∞.

03

Take or skip

Scan in order: if start ≥ lastEnd, take it and set lastEnd to its end; otherwise skip — it overlaps.

04

Optimal by exchange

The earliest finisher is always safe to include, so the greedy set is a maximum set.

Time
O(n log n)
Space
O(1)
Criterion
Earliest finish
Result
Max count

This is the textbook example of a greedy that is provably optimal, alongside Huffman coding, Kruskal and Dijkstra. It solves single-resource scheduling everywhere: booking one meeting room, sequencing jobs on one machine, assigning a taxi to non-overlapping rides. Change the goal to maximum total weight instead of maximum count, though, and greedy breaks — weighted interval scheduling needs dynamic programming (sort by finish, then for each interval take it plus the best compatible earlier solution, located with a binary search).

Check yourself

1 · To maximize non-overlapping intervals, sort by…

Finishing soonest frees the resource earliest, leaving the most room. It is the only criterion that is provably optimal for maximizing the count.

2 · When do you take the next interval?

If the start clears the last finish, there is no overlap, so take it and advance lastEnd. Otherwise it conflicts and is skipped.

3 · Why is sorting by shortest interval wrong?

One tiny interval sitting across the boundary of two longer ones can knock both out, losing a better pair. Earliest-finish avoids this trap.

The picture: six meetings, one room

0123456789101-32-54-76-85-98-10kept: 1-3, 4-7, 8-10 (3 meetings)
The page’s six intervals drawn on a time line and listed in finish order. Highlighted bars are the ones the greedy scan keeps; red bars overlap the last kept one and are skipped. Each kept bar starts at or after the end of the previous kept bar, so the three never share a moment, and the brute-force best over all 64 subsets is also 3.

Worked example, step by step

The input is [[1,3], [2,5], [4,7], [6,8], [5,9], [8,10]], which is already in order of finish time (3, 5, 7, 8, 9, 10). Keep last_end, the finish of the most recent meeting you took, starting at −∞. For each interval, take it if its start is at least last_end.

Intervallast_endTestDecisionTaken so farlast_end after
1–3−∞1 ≥ −∞: yestake13
2–532 < 3: overlapsskip13
4–734 ≥ 3: yestake27
6–876 < 7: overlapsskip27
5–975 < 7: overlapsskip27
8–1078 ≥ 7: yestake310

The scan took 3 meetings: [1, 3], [4, 7], [8, 10]. The skipped intervals show why finish order matters. [2, 5] starts before the room frees at 3, so it is out. [6, 8] and [5, 9] start before 7. Every decision is made once, with no look-ahead and no backtracking, because the exchange argument guarantees that taking the earliest finisher never closes off a better schedule. This particular input does not separate the rules: earliest start first also keeps 3 (1-3, 4-7, 8-10) and shortest first keeps 3 (1-3, 6-8, 8-10). They are not equivalent, though. They only agree here by luck, and the mistakes below give small inputs where each is plainly wrong.

Complexity and trade-offs

CaseTimeSpaceWhy
Greedy by earliest finishO(n log n)O(1) extraThe sort dominates; the scan is one pass. If the input is already sorted by finish, it is O(n).
Try every subsetO(2ⁿ · n)O(n)Correct but hopeless: 6 intervals means 64 subsets, 30 intervals means 1,073,741,824.
Weighted version, DPO(n log n)O(n)Sort by finish, then for each interval best = max(skip it, its weight + best of the last compatible one, found by binary search).
Fewest rooms for all meetings (a different question)O(n log n)O(n)Sort by start and keep a heap of end times. It schedules everything rather than choosing a subset.

The greedy rule gives up one thing: it only maximises the count. The moment intervals carry different values, the exchange argument stops working and you need the weighted DP, which costs a binary search per interval and linear extra memory. The same exchange argument also answers the mirror question, “how few intervals must I remove so the rest do not overlap”: it is n minus the maximum kept, which is 6 − 3 = 3 for this input.

Common mistakes

  • Sorting by start time

    On [[1,10],[2,3],[4,5]] earliest-start takes the long meeting [1, 10] first and then nothing fits: 1 meeting. Earliest-finish gets 2.

  • Sorting by shortest duration

    On [[1,5],[4,6],[5,10]] the short meeting [4, 6] sits across the boundary of the other two and blocks both. Shortest-first keeps 1; earliest-finish keeps 2.

  • Using > instead of >= in the test

    Meetings that touch at an endpoint do not overlap. With a strict test, [[1,2],[2,3],[3,4]] keeps 2 meetings instead of 3. (If the problem says a meeting needs a gap, the strict test is the right one, so read the statement.)

  • Updating last_end on a skipped interval

    Only a taken interval moves the frontier. Setting last_end on every interval makes the scan chase intervals it rejected; on the page’s input it keeps 1 instead of 3.

  • Using the greedy rule when intervals have weights

    Given [1, 3] worth 1 and [2, 5] worth 10, the count-greedy takes the first and totals 1; the best schedule takes the second and totals 10. Weighted problems need the DP.

Where this shows up

  • Booking one resource

    One meeting room, one operating theatre, one lecture hall or one machine, with a pile of requests and the goal of serving as many as possible. This is the textbook activity-selection problem.

  • Minimum removals to make intervals disjoint

    Deciding which bookings to cancel so that the rest do not collide is the same computation, answered as n minus the greedy count.

  • Covering with the fewest points

    Choosing the fewest points that touch every interval (for example, the fewest times to fire at a row of overlapping targets) sorts by finish and takes the end of each interval not yet covered, by the same exchange argument.

  • A building block for harder scheduling

    Weighted job scheduling, multi-room allocation and interval partitioning all start from the same sort-by-finish or sort-by-start step, and knowing when greedy stops being valid is the real lesson.

SOLVE IT YOURSELF

Solve it: fit the most meetings in one room

The obvious greedy choices — shortest meeting, earliest start — both give wrong answers. One greedy choice is provably optimal. Write it in Python or TypeScript, running for real in your browser.

YOUR TASK

Implement max_meetings(intervals): given [start, end] pairs, return the largest number of non-overlapping meetings that fit in one room. A meeting starting exactly when another ends is fine.

HINTS — 5 IDEAS
  1. Sort by end time, ascending. Not start time, not duration.
  2. Why: finishing earliest leaves the maximum remaining room for everything else. Any other choice can be swapped for this one without making the answer worse.
  3. Sweep the sorted list, tracking last_end. Take a meeting whenever start >= last_end, and update last_end.
  4. Use >=, not > — back-to-back meetings do not overlap.
  5. Counter-example worth trying: [[1,10],[2,3],[4,5]]. Earliest-start takes the long one and gets 1; earliest-end gets 2.
CPython · WebAssembly

Questions

Why not just pick the shortest intervals?

Because a single short interval can overlap two longer ones that do not overlap each other, blocking both and costing you a selection. Earliest-finish-first has a clean exchange-argument proof of optimality; shortest-first and earliest-start-first do not.

What if intervals have weights or values?

Then you want maximum total weight, not maximum count, and greedy fails. Weighted interval scheduling is a dynamic-programming problem: sort by finish, and for each interval choose the better of skipping it or taking it plus the best solution that ends before it starts (found with binary search).

Where does this show up in practice?

Anywhere one resource is shared over time: reserving a single meeting room, scheduling jobs on one machine, matching one vehicle to non-overlapping trips. It is also a warm-up for interval problems like merging intervals and finding the minimum number of rooms.

Sort by finish, and greed is optimal.

Take the interval that ends soonest, skip whatever it overlaps, repeat — and you have fit the maximum number into one resource.

Finished this one? 0 / 99 Algorithms done
NextFrequent Symbols, Short Codes: Huffman Coding Next on the “When greedy is provably enough” ladder · rung 2 of 3

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms