Greedy Pattern

Recognise interview problems where a local choice is provably optimal — jump game, gas station, interval scheduling, candy, and when greedy fails.

Intermediate 3 min readLesson 22 of 25

A greedy algorithm makes the locally best choice at each step and never reconsiders. When it works, it's usually the simplest and fastest solution, often O(n) or O(n log n). The hard part is knowing when it works. (Proof techniques: Greedy algorithms.)

When to use this pattern
  • "Minimum number of…", "maximum number of non-overlapping…", "can you reach…".
  • Sorting by one key (end time, deadline, ratio) seems to make the rest obvious.
  • Small examples never seem to need you to "go back" on a choice.
  • If a counterexample appears, switch to dynamic programming.

Recurring greedy shapes

ShapeGreedy ruleExample
ReachabilityTrack the farthest index reachable so farJump Game
Fewest jumpsBFS by "levels" of reachJump Game II
Interval schedulingSort by end; take what fitsNon-overlapping Intervals, Arrows
Running balanceReset the start when the balance goes negativeGas Station, Kadane
Two passesSatisfy the left constraint, then the rightCandy, Trapping Rain Water
Sort then matchPair smallest with smallest (or largest)Assign Cookies, Boats to Save People
Counting slotsThe most frequent item dictates the layoutTask Scheduler, Reorganize String

Jump game I & II

boolean canJump(int[] a) {
    int far = 0;
    for (int i = 0; i < a.length; i++) {
        if (i > far) return false;                 // stuck before reaching i
        far = Math.max(far, i + a[i]);
    }
    return true;
}

int jump(int[] a) {                                // min jumps to reach the end
    int jumps = 0, end = 0, far = 0;
    for (int i = 0; i < a.length - 1; i++) {
        far = Math.max(far, i + a[i]);
        if (i == end) { jumps++; end = far; }      // current "level" exhausted
    }
    return jumps;
}

Gas station

If total gas ≥ total cost, a solution exists. Whenever the running tank drops below zero at station i, no station between the current start and i can work, so restart from i + 1.

int canCompleteCircuit(int[] gas, int[] cost) {
    int total = 0, tank = 0, start = 0;
    for (int i = 0; i < gas.length; i++) {
        int d = gas[i] - cost[i];
        total += d; tank += d;
        if (tank < 0) { start = i + 1; tank = 0; }
    }
    return total >= 0 ? start : -1;
}

Two-pass greedy: candy

Each child gets at least one candy, and a child rated higher than a neighbour gets more than that neighbour. Pass left to right fixing the left neighbour, then right to left taking max(current, right + 1).

int candy(int[] r) {
    int n = r.length;
    int[] c = new int[n];
    Arrays.fill(c, 1);
    for (int i = 1; i < n; i++) if (r[i] > r[i - 1]) c[i] = c[i - 1] + 1;
    for (int i = n - 2; i >= 0; i--) if (r[i] > r[i + 1]) c[i] = Math.max(c[i], c[i + 1] + 1);
    return Arrays.stream(c).sum();
}

When greedy fails

Greedy works
  • Coin change with coins 1, 5, 10, 25
  • Activity selection by earliest end
  • Fractional knapsack by value/weight
  • Huffman coding
Greedy fails
  • Coin change with coins 1, 3, 4 (amount 6: greedy 4+1+1, optimal 3+3)
  • Activity selection by earliest start or shortest duration
  • 0/1 knapsack
  • Longest path in a general graph
Practice problems
  • Assign Cookieseasy
  • Best Time to Buy and Sell Stock IIsum every risemedium
  • Jump Gamemedium
  • Jump Game IImedium
  • Gas Stationmedium
  • Partition Labelslast occurrence of each charmedium
  • Non-overlapping Intervalssort by endmedium
  • Minimum Number of Arrows to Burst Balloonsmedium
  • Boats to Save Peopletwo pointers after sortmedium
  • Hand of Straightsmedium
  • Candytwo passeshard
  • Minimum Number of Refueling Stopsgreedy + max-heaphard
Key takeaways
  • Greedy = a local choice you never undo; correct only with the greedy-choice property.
  • Typical moves: track the farthest reach, sort by end time, reset a negative running balance, two passes.
  • Prove it with an exchange argument; otherwise look for a counterexample and use DP.