Skip to content

Greedy methods and interval selection

A greedy algorithm commits to a local choice without reconsidering earlier choices. The proof must show that this commitment preserves an optimal answer. A rule that produces a valid answer can still miss the best answer.

This lesson selects requests for one instrument. Each invented request has a fixed start and finish time. Read sorting and intervals for interval boundaries and Big O for the cost of a sorted copy.

Return a largest set of compatible requests. Each request contributes one to the objective, regardless of its duration. A request occupies the half-open interval [start, finish), with start < finish. A request can start when the previous request finishes. The instrument handles one request at a time.

The empty input returns an empty list. Duplicate requests remain separate candidates, but their positive durations prevent selecting both. The function keeps the input unchanged and returns selected intervals in execution order.

Sort requests by finish time, then accept a request when its start is at least the last selected finish. A secondary start-time key makes ties deterministic.

def finish_key(interval: tuple[int, int]) -> tuple[int, int]:
"""Return finish and start coordinates for deterministic sorting.
Args:
interval: Start and finish coordinates of a request.
Returns:
The finish coordinate followed by the start coordinate.
"""
start, finish = interval
return finish, start
def select_requests(
intervals: list[tuple[int, int]],
) -> list[tuple[int, int]]:
"""Select a maximum number of compatible positive-duration requests.
Args:
intervals: Half-open integer intervals with start below finish.
Returns:
Selected intervals in execution order, without changing the input.
Raises:
ValueError: If a request has zero or negative duration.
"""
for start, finish in intervals:
if start >= finish:
raise ValueError("each request must start before it finishes")
selected: list[tuple[int, int]] = []
last_finish: int | None = None
for start, finish in sorted(intervals, key=finish_key):
if last_finish is None or start >= last_finish:
selected.append((start, finish))
last_finish = finish
return selected
requests = [(5, 8), (0, 9), (1, 3), (3, 5), (6, 7), (7, 10)]
last_finish = None
print("request | previous finish | decision")
for request in sorted(requests, key=finish_key):
start, finish = request
accept = last_finish is None or start >= last_finish
print(request, last_finish, "accept" if accept else "reject", sep=" | ")
if accept:
last_finish = finish
print("Selected requests:", select_requests(requests))
print("Original requests:", requests)
request | previous finish | decision
(1, 3) | None | accept
(3, 5) | 3 | accept
(6, 7) | 5 | accept
(5, 8) | 7 | reject
(0, 9) | 7 | reject
(7, 10) | 7 | accept
Selected requests: [(1, 3), (3, 5), (6, 7), (7, 10)]
Original requests: [(5, 8), (0, 9), (1, 3), (3, 5), (6, 7), (7, 10)]

The selected requests remain compatible after every iteration. The stronger invariant states that some optimal schedule begins with the selected requests. That second statement explains why the result is optimal, rather than only valid.

Consider an optimal schedule for the requests that remain compatible with the selected prefix. Let its first request be other. Let greedy be the compatible request that finishes earliest.

Replace other with greedy. The replacement finishes no later, so every later request remains compatible. The number of selected requests stays the same. An optimal schedule therefore exists with this greedy first choice. Repeat the argument on the remaining compatible requests.

The scan rejects a request only when it conflicts with the selected prefix. When the scan ends, no compatible schedule has more requests. The proof depends on the count objective and the fixed interval boundaries.

An earliest-start rule can occupy the instrument for an entire sequence of shorter requests. The following code demonstrates that failed rule on one input. It is a counterexample, not an alternative solution.

counterexample = [(0, 9), (1, 3), (3, 5), (5, 7)]
start_first: list[tuple[int, int]] = []
for start, finish in sorted(counterexample):
if not start_first or start >= start_first[-1][1]:
start_first.append((start, finish))
finish_first = select_requests(counterexample)
print("Earliest-start selection:", start_first)
print("Earliest-finish selection:", finish_first)
print("Selected counts:", len(start_first), len(finish_first))
assert len(start_first) < len(finish_first)
Earliest-start selection: [(0, 9)]
Earliest-finish selection: [(1, 3), (3, 5), (5, 7)]
Selected counts: 1 3

A counterexample needs one input where a rule fails. A correctness proof must cover every input allowed by the problem. Successful examples alone cannot justify a greedy choice.

If requests have different rewards, the earliest-finish proof no longer preserves the objective. Exchanging one request for another preserves their count but can reduce their total reward.

weighted_requests = [(0, 2, 1), (2, 4, 1), (0, 4, 5)]
intervals = [(start, finish) for start, finish, reward in weighted_requests]
rewards = {
(start, finish): reward for start, finish, reward in weighted_requests
}
count_selection = select_requests(intervals)
count_reward = sum(rewards[request] for request in count_selection)
long_request_reward = rewards[(0, 4)]
print("Count-optimal selection:", count_selection)
print("Its total reward:", count_reward)
print("Reward from the long request:", long_request_reward)
assert count_reward < long_request_reward
Count-optimal selection: [(0, 2), (2, 4)]
Its total reward: 2
Reward from the long request: 5

Weighted interval selection needs another argument or algorithm. A standard dynamic program compares each request’s reward plus a compatible prefix with the value from skipping that request. The dynamic programming lesson explains how to define such prefix states.

For n requests, input checks take O(n) time. Sorting takes O(n log n) worst-case time, and the selection scan takes O(n) time. These bounds assume constant-time comparisons between the integer endpoints.

The sorted copy and Python’s sort workspace require O(n) auxiliary space. The returned selection occupies up to O(n) output space. If the input already has the required order, a separate scan can avoid the sort and its copy.

assert select_requests([]) == []
assert select_requests([(2, 4)]) == [(2, 4)]
assert select_requests([(1, 3), (1, 3)]) == [(1, 3)]
assert select_requests([(0, 2), (2, 4)]) == [(0, 2), (2, 4)]
assert select_requests([(-5, -2), (-2, 0)]) == [(-5, -2), (-2, 0)]
assert select_requests([(0, 8), (2, 3), (4, 5)]) == [(2, 3), (4, 5)]
for invalid in ([(2, 2)], [(4, 1)]):
try:
select_requests(invalid)
except ValueError as error:
print(type(error).__name__, str(error))
else:
raise AssertionError("an invalid interval was accepted")
print("Empty, duplicate, touching, negative, and contained cases passed.")
ValueError each request must start before it finishes
ValueError each request must start before it finishes
Empty, duplicate, touching, negative, and contained cases passed.

Non-overlapping Intervals asks for the minimum number of removals. Relate that answer to the largest compatible subset, and state its rule for touching endpoints.

Maximum Length of Pair Chain requires a strict gap between consecutive pairs. Adjust the compatibility comparison and explain why the endpoint change does not change the exchange argument.

Download the Python source to run the complete example locally.

MIT’s interval scheduling notes compare candidate rules and prove the earliest-finish choice. Use the proof to identify the exact assumption that fails for unequal rewards.

Python’s sorting guide explains key functions and stable ordering. It helps separate the ordering rule from the decision to accept a request.