Greedy Pattern
Recognise interview problems where a local choice is provably optimal — jump game, gas station, interval scheduling, candy, and when greedy fails.
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.)
- "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
| Shape | Greedy rule | Example |
|---|---|---|
| Reachability | Track the farthest index reachable so far | Jump Game |
| Fewest jumps | BFS by "levels" of reach | Jump Game II |
| Interval scheduling | Sort by end; take what fits | Non-overlapping Intervals, Arrows |
| Running balance | Reset the start when the balance goes negative | Gas Station, Kadane |
| Two passes | Satisfy the left constraint, then the right | Candy, Trapping Rain Water |
| Sort then match | Pair smallest with smallest (or largest) | Assign Cookies, Boats to Save People |
| Counting slots | The most frequent item dictates the layout | Task 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;
}def can_jump(a):
far = 0
for i, x in enumerate(a):
if i > far:
return False
far = max(far, i + x)
return True
def jump(a):
jumps = end = far = 0
for i in range(len(a) - 1):
far = max(far, i + a[i])
if i == end:
jumps += 1
end = far
return jumpsfunction canJump(a: number[]): boolean {
let far = 0;
for (let i = 0; i < a.length; i++) {
if (i > far) return false;
far = Math.max(far, i + a[i]);
}
return true;
}
function jump(a: number[]): number {
let jumps = 0, end = 0, far = 0;
for (let i = 0; i < a.length - 1; i++) {
far = Math.max(far, i + a[i]);
if (i === end) { jumps++; end = far; }
}
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;
}def can_complete_circuit(gas, cost):
total = tank = start = 0
for i, (g, c) in enumerate(zip(gas, cost)):
total += g - c
tank += g - c
if tank < 0:
start, tank = i + 1, 0
return start if total >= 0 else -1function canCompleteCircuit(gas: number[], cost: number[]): number {
let total = 0, tank = 0, start = 0;
for (let i = 0; i < gas.length; i++) {
const 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();
}def candy(r):
n = len(r)
c = [1] * n
for i in range(1, n):
if r[i] > r[i - 1]:
c[i] = c[i - 1] + 1
for i in range(n - 2, -1, -1):
if r[i] > r[i + 1]:
c[i] = max(c[i], c[i + 1] + 1)
return sum(c)function candy(r: number[]): number {
const n = r.length, c = new Array(n).fill(1);
for (let i = 1; i < n; i++) if (r[i] > r[i - 1]) c[i] = c[i - 1] + 1;
for (let i = n - 2; i >= 0; i--) if (r[i] > r[i + 1]) c[i] = Math.max(c[i], c[i + 1] + 1);
return c.reduce((s, x) => s + x, 0);
}When greedy fails
- Coin change with coins 1, 5, 10, 25
- Activity selection by earliest end
- Fractional knapsack by value/weight
- Huffman coding
- 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
- 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
- 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.