Skip to content
DSA Patterns
Menu
Language

Pattern #21

Greedy

Recommended

Make 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.

Step 1 of 8
1/8

Jump Game: track the farthest index reachable so far.

far
2
0
3
1
1
2
1
3
4
4
Statei=0far=0

far = 0

Key:CurrentActive rangeMatchSettledEliminated

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

  1. Jumps expand far only through the index before the last. Spend a jump when i reaches the current end (LC 45). Reachability fails when i passes far (LC 55).
  2. Gas resets the start to i + 1 when the tank would go negative. That start works only when the total is non-negative (LC 134).
  3. Removals sort by end, not by start. A start that only touches keptEnd is kept (LC 435).
  4. Labels push end to the last index of the current character. A part closes when i catches end (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
/** 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;
}
#StatusProblemTypeDone
  1. 1#45 Jump Game IIGuide
  2. 2#55 Jump GameGuide
  3. 3#134 Gas StationGuide
  4. 4#435 Non-overlapping IntervalsGuide
  5. 5#621 Task SchedulerGuide
  6. 6#763 Partition LabelsGuide