Pattern #21
Greedy
RecommendedMake the best local choice when you can prove it never ruins the global optimum.
When to use
After sorting or a clear priority, a single forward pass decides irrevocably and stays optimal (exchange argument).
Recognition cues
- Jump game / jump game II
- Gas station / task scheduler
- Sort then scan / earliest end first
Common pitfalls
- Greedy without a proof (counterexamples exist)
- Wrong sort key
- Confusing greedy with DP when future choices interact
90-second recognition drill
Which pattern fits best?
- Jump game / jump game II
- Gas station / task scheduler
- Sort then scan / earliest end first
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
far = 0
How to think about it
Identify a score for each choice (farthest reach, earliest finish, largest gain). Sort or scan so the next pick is obvious. Prove that swapping any other pick for yours cannot improve the answer (exchange argument).
Template shapes
| Shape | Core move | Example |
|---|---|---|
| Minimum jumps | Each index before the last expands far to i + nums[i]. When i reaches the current jump’s end, one jump is spent and that end moves to far |
LC 45 |
| Can reach | far is max(far, i + nums[i]). If i moves past far, the end is unreachable |
LC 55 |
| Gas circuit | total adds gas[i] - cost[i]. A negative tank resets to 0 and the candidate start becomes i + 1. A non-negative total means that start finishes the circuit |
LC 134 |
| Minimum removals | Sort by end. If the next start is strictly before keptEnd, discard it. Otherwise that end becomes keptEnd |
LC 435 |
| Task gaps | The busiest task appears maxf times, and maxCount tasks share that count. Between the blocks sit maxf - 1 gaps of n - (maxCount - 1) slots. The answer is the number of tasks plus the idle slots that other tasks do not fill |
LC 621 |
| Partition labels | last[c] is the last index of character c. One scan pushes end out to last[s[i]]. When i catches end, [start, end] is one part |
LC 763 |
Complexity baseline
Often O(n log n) for a sort plus an O(n) scan, or a pure O(n) scan. Jumps, gas, tasks, and labels do not sort.
From template to problem
- Jumps expand
faronly through the index before the last. Spend a jump whenireaches the current end (LC 45). Reachability fails whenipassesfar(LC 55). - Gas resets the start to
i + 1when the tank would go negative. That start works only when the total is non-negative (LC 134). - Removals sort by end, not by start. A start that only touches
keptEndis kept (LC 435). - Labels push
endto the last index of the current character. A part closes whenicatchesend(LC 763). Idle slots are what remains after other tasks fill the gaps between the busiest task (LC 621).
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
/** Greedy template: Jump Game (farthest reach). Track far; fail if i > far. */
export function canJump(nums: number[]): boolean {
let far = 0;
for (let i = 0; i < nums.length; i++) {
if (i > far) return false;
far = Math.max(far, i + nums[i]!);
if (far >= nums.length - 1) return true;
}
return true;
}
/** Greedy template: Jump Game (farthest reach). Track far; fail if i > far. */
export function canJump(nums: number[]): boolean {
let far = 0;
for (let i = 0; i < nums.length; i++) {
if (i > far) return false;
far = Math.max(far, i + nums[i]!);
if (far >= nums.length - 1) return true;
}
return true;
}
- 1#45 Jump Game IIGuidemedium
- 2#55 Jump GameGuidemedium
- 3#134 Gas StationGuidemedium
- 4#435 Non-overlapping IntervalsGuidemedium
- 5#621 Task SchedulerGuidemedium
- 6#763 Partition LabelsGuidemedium