Greedy algorithms choose the best local move at each step and never revisit past choices.

They are fast and elegant when valid, but easy to misuse. Interviewers care about one thing:

Can you justify why local optimal choices lead to a global optimum?

How to validate a greedy strategy

Common proof styles:

  • Exchange argument: show any optimal solution can be transformed to match greedy choice without getting worse
  • Staying-ahead argument: after each step, greedy is at least as good as any other strategy

If you cannot justify with one of these, greedy may be wrong.

Pattern 1: Interval scheduling

Problem: maximum number of non-overlapping intervals.

Greedy rule: sort by end time, always pick earliest finishing interval.

export function maxNonOverlapping(intervals: Array<[number, number]>): number {
  intervals.sort((a, b) => a[1] - b[1]);
  let count = 0;
  let currentEnd = Number.NEGATIVE_INFINITY;

  for (const [start, end] of intervals) {
    if (start >= currentEnd) {
      count++;
      currentEnd = end;
    }
  }

  return count;
}

Reason: earliest finishing leaves maximum room for remaining intervals.

Pattern 2: Jump game (reachability)

Track farthest reachable index while scanning left to right.

export function canJump(nums: number[]): boolean {
  let farthest = 0;

  for (let i = 0; i < nums.length; i++) {
    if (i > farthest) return false;
    farthest = Math.max(farthest, i + nums[i]!);
    if (farthest >= nums.length - 1) return true;
  }

  return true;
}

Local best is updating farthest coverage.

Pattern 3: Minimum arrows to burst balloons

Equivalent to interval overlap groups. Sort by end, greedily shoot at current end.

Pattern 4: Activity selection with sorting keys

Many greedy solutions begin with sorting:

  • By end time
  • By start time
  • By value density (value / weight) for fractional knapsack

Key interview skill: identify which ordering supports safe local decisions.

Common greedy pitfalls

  • Picking the largest immediate gain without proof
  • Ignoring edge constraints that break monotonic behavior
  • Assuming sorting by one attribute always works
  • Confusing fractional knapsack (greedy works) with 0/1 knapsack (needs DP)

Greedy vs DP quick test

  • If local decisions can lock out better future combinations, DP is likely needed
  • If you can prove exchange or staying-ahead, greedy is likely valid

Practice set

  • Non-overlapping intervals
  • Merge intervals
  • Jump game I and II
  • Gas station
  • Partition labels
  • Task scheduler (with heap + greedy)

Greedy interviews are mostly proof exercises. Implementation is usually short once the argument is sound.