Commit to a local choice only after proving an optimum can include it. Match the objective and compatibility rule to an exchange argument; interval scheduling is one example, not a universal scoring recipe.
Recognize it when A legal choice permanently settles part of the remaining work.
Checking your account…
Greedy Code Labs
Make One Irreversible Local Choice
A greedy algorithm commits to one locally best option and never revisits it. The implementation is easy; proving that commitment preserves a global optimum is the real work.
State the Exchange Argument
Show that any optimal solution can replace its first differing choice with the greedy choice without becoming worse. Repeating that exchange transforms an optimum into the greedy solution.
Trace Earliest-Finish Choices
Reference
def interval_choice_trace(intervals):
trace=[]; last_end=None
for interval in sorted(intervals,key=lambda item:(item[1],item[0])):
accepted=last_end is None or interval[0]>=last_end
trace.append([interval.copy(),accepted])
if accepted:last_end=interval[1]
return trace
Practice
Implement interval_choice_trace(intervals). Sort by end and return [interval,accepted] decisions for non-overlapping selection. Supply positive-duration half-open intervals with start < end; touching endpoints do not overlap.
Public tests
Commit to earliest finish
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Trace Earliest-Finish Choices
def interval_choice_trace(intervals):
trace=[]; last_end=None
for interval in sorted(intervals,key=lambda item:(item[1],item[0])):
accepted=last_end is None or interval[0]>=last_end
trace.append([interval.copy(),accepted])
if accepted:last_end=interval[1]
return trace
Keep the End of the Accepted Interval
The existing trace Lab receives a tempting long interval and two shorter compatible ones. Predict the sorted order before evaluating compatibility, then track only accepted end updates.
Step
Executed statement
State
Why
Sort by finish
for interval in sorted(intervals,key=lambda item:(item[1],item[0])):
order=[1,2],[2,4],[0,9]
The decision key exposes the earliest-finishing compatible candidate.
First acceptance
accepted=last_end is None or interval[0]>=last_end;trace.append([interval.copy(),accepted]);last_end=interval[1]
last_end=2, first row True
No prior choice restricts the first candidate.
Touching acceptance
accepted=last_end is None or interval[0]>=last_end;trace.append([interval.copy(),accepted]);last_end=interval[1]
last_end=4, second row True
The second starts exactly where the first half-open interval ends.
Reject long interval
accepted=last_end is None or interval[0]>=last_end;trace.append([interval.copy(),accepted])
third row False; last_end remains 4
Rejection does not alter compatibility state.
Print
Output
print(interval_choice_trace([[0,9],[1,2],[2,4]]))
[[[1, 2], True], [[2, 4], True], [[0, 9], False]]
The exchange proves the count objective. Adding profits invalidates this particular proof: a rejected long interval could be worth more than several short ones. Choose weighted scheduling DP for that changed problem.
Sort by the Decision Key
Sorting exposes the choice order required by the proof. For interval scheduling, earliest finish leaves at least as much room for every future interval as any later finish.
Select Maximum Compatible Intervals
Reference
def max_compatible_intervals(intervals):
count=0;last_end=None
for start,end in sorted(intervals,key=lambda item:(item[1],item[0])):
if last_end is None or start>=last_end:count+=1;last_end=end
return count
Practice
Implement max_compatible_intervals(intervals). Return the maximum count of non-overlapping half-open intervals. Supply positive-duration half-open intervals with start < end; touching endpoints do not overlap.
Public tests
Leave maximum room for future choices
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Select Maximum Compatible Intervals
def max_compatible_intervals(intervals):
count=0;last_end=None
for start,end in sorted(intervals,key=lambda item:(item[1],item[0])):
if last_end is None or start>=last_end:count+=1;last_end=end
return count
Know When Greedy Fails
A plausible local score is insufficient. If choices change future value in ways the exchange cannot preserve, use dynamic programming, search, or backtracking. Test a small counterexample before committing.
Explain It in an Interview
Say: “I choose the earliest finish. Given any optimal schedule, exchanging its first interval for mine cannot reduce remaining room, so an optimum with my choice exists.” Count sorting plus the linear scan and state endpoint semantics.
Template To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
Greedy farthest reach
Track the farthest reach; fail if you fall behind it.
Each position lets you jump or extend up to some distance, and you ask whether (or how fast) you can reach the end.
Trigger words
jump game
reach the last index
minimum jumps
gas station
partition labels
farthest reach
def can_jump(nums):
farthest = 0 # farthest index reachable so far
for i, step in enumerate(nums):
if i > farthest:
return False # we can never stand on index i
farthest = max(farthest, i + step)
return True
Spot it when
'Can you reach the last index?'
'Minimum number of jumps'.
Covering a range with as few pieces as possible.
Remember
farthest only grows, so one left-to-right pass is enough: O(n).
The check i > farthest comes before you use nums[i].
How problems bend it
Minimum number of jumps: Keep the end of the current jump; when i reaches it, count a jump and set end = farthest.
Gas station: If the tank drops below zero, start again from the next station; a full answer exists only if total gas >= total cost.
Python Version Note
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Greedy proof does not depend on a minor Python release.