Skip to contentKEEP THE CRAFTTHE SANCTUARY

Greedy

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.

10 practice exercises14 interview problems

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

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Unweighted interval schedulingO(n log n)O(n log n)Sorting by (end,start) plus a linear scan; already sorted input helps only when sorting is omitted.

Space

O(n) sorted list and decision trace; counting scan uses O(1) extra state beyond sorting.

Assumptions

  • The same greedy family includes MST cut choices but uses different state and proof.
  • Endpoint equality is compatible here because intervals are half-open.

Invariants Worth Saying Aloud

  1. The chosen prefix can extend to an optimal full solution.
  2. The last accepted end summarizes compatibility for this unweighted interval problem.
  3. Rejected intervals overlap the current accepted end; they do not advance it.

When To Use Or Avoid Greedy

Use It When

  • Use earliest finish for the maximum number of compatible unweighted intervals.
  • Use a different proven rule for a different objective; weighted intervals usually need DP.

Choose Another Tool When

  • A shortest interval, earliest start or largest profit score alone does not prove correctness.
  • Reusable coin systems are not all canonical for largest-coin-first selection.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Choosing by earliest start

The interval [0,10] starts first but blocks [1,2] and [2,3]. The smallest start leaves less useful room.

Prevent it: Sort by finish for maximum unweighted count.

Avoid

first=min(intervals)

Use instead

first=min(intervals,key=lambda item:(item[1],item[0]))

Rejecting touching half-open intervals

[1,3) and [3,5) share no time point. A strict start comparison incorrectly rejects the second.

Prevent it: Use start >= last_end for this contract.

Avoid

accepted=start>last_end

Use instead

accepted=start>=last_end

Updating last end after a rejection

A rejected [0,9] must not move last_end from 2 to 9, or the next compatible [2,4] is lost.

Prevent it: Change last_end only inside the acceptance branch.

Avoid

last_end=end

Use instead

if accepted:
    last_end=end

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.