Tensorum

Greedy

Intervals, scheduling and reachability, with exchange arguments to prove each choice.

DSAIntermediate18 hrs5 patterns · 28 problems
0%
your progress

Core idea

Sort by the key that makes a local choice safe (usually end time), then commit. Validate with an exchange argument: swapping in the greedy choice never makes things worse.

Reach for it when

  • Interval scheduling, merging and covering
  • Reachability (jump games)
  • Exchange arguments make the choice obvious

Template

def max_non_overlapping(intervals):
    intervals.sort(key=lambda x: x[1])
    count, end = 0, float('-inf')
    for s, e in intervals:
        if s >= end:
            count, end = count + 1, e
    return count

Complexity

Typically O(n log n) for the sort plus O(n) scan.

Common pitfalls

  • Sorting by start when the proof needs end
  • Applying greedy where DP is required (coin change with arbitrary coins)
  • Not testing on small counter-examples

Recognition cues

IntervalsSchedulingJump/ReachabilityLocal ChoiceTwo-pass