Take the best next step—with a reason.
Know when a local choice has a global correctness argument.
01 Model the idea
A greedy algorithm commits to a local choice without revisiting it. That is a design pattern, not proof of optimality. For maximising the number of nonoverlapping positive-duration intervals, choosing the earliest finishing compatible interval has an exchange argument: replacing an optimal solution’s first interval with the earliest finisher leaves at least as much room for the rest. Other objectives, such as weighted value, need a different argument or algorithm.
The chosen set stays feasible and leaves maximum remaining time after each greedy choice.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
SORT by increasing finish time
ACCEPT each interval compatible with the last accepted end03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def select_intervals(intervals):
chosen, end = [], float("-inf")
for name, start, finish in sorted(intervals, key=lambda item: item[2]):
if start >= finish: raise ValueError("Positive-duration intervals required")
if start >= end:
chosen.append(name); end = finish
return chosen
print(select_intervals([("long", 0, 10), ("A", 0, 2), ("B", 2, 4), ("C", 4, 6)]))['A', 'B', 'C']
- 1
The sort makes the local rule explicit. A half-open interval may begin exactly when the previous interval finishes.
- 2
The objective is number of accepted intervals, not total duration or revenue. Changing the objective can invalidate the same greedy rule.
- 3
Look for an exchange argument or another proof before relying on a plausible heuristic. A counterexample is often easier to find than a full proof, so test small adversarial cases.
04 Count the cost
O(n log n) sorting plus O(n) scan
O(n) sorted input copy and result
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Give a counterexample to selecting the earliest-starting interval first.
Reveal one possible solution +
intervals = [("long", 0, 10), ("A", 1, 2), ("B", 2, 3)]
earliest_start_count = 1
earliest_finish_count = 2
assert earliest_finish_count > earliest_start_count
print("A then B beats long")06 Check your reasoning
What makes a greedy rule trustworthy?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.