Pattern #32

Greedy Algorithms

Important interview questions, thinking patterns, Activity Selection, Jump Game, Gas Station, exchange argument proofs, and Go rules.

Must Solve

20 core questions — solve these first.

  1. 1.Best Time to Buy and Sell Stock II
    medium
  2. 2.Jump Game
    medium
  3. 3.Jump Game II
    medium
  4. 4.Gas Station
    medium
  5. 5.Candy
    hard
  6. 6.Assign Cookies
    easy
  7. 7.Lemonade Change
    easy
  8. 8.Non-overlapping Intervals
    medium
  9. 9.Minimum Number of Arrows to Burst Balloons
    medium
  10. 10.Partition Labels
    medium
  11. 11.Task Scheduler
    medium
  12. 12.Queue Reconstruction by Height
    medium
  13. 13.Boats to Save People
    medium
  14. 14.Can Place Flowers
    easy
  15. 15.Maximum Units on a Truck
    easy
  16. 16.Bag of Tokens
    medium
  17. 17.Remove K Digits
    medium
  18. 18.Reorganize String
    medium
  19. 19.Hand of Straights
    medium
  20. 20.Minimum Cost to Connect Sticks
    medium

Also Important

10 more questions worth practicing.

  1. 21.Two City Scheduling
    medium
  2. 22.Maximum Length of Pair Chain
    medium
  3. 23.Wiggle Subsequence
    medium
  4. 24.Valid Parenthesis String
    medium
  5. 25.Minimum Deletions to Make Character Frequencies Unique
    medium
  6. 26.Furthest Building You Can Reach
    medium
  7. 27.IPO
    hard
  8. 28.Minimum Number of Refueling Stops
    hard
  9. 29.Course Schedule III
    hard
  10. 30.Activity Selection Problem
    medium

How to Think

  1. Need best local choice each step?Greedy Algorithm
  2. Need maximum non-overlapping intervals?Sort by END time + Greedy selection
  3. Need minimum resources / cost?Take cheapest / earliest / best available
  4. Can current bad decision be fixed later?No! Greedy commits permanently without undo
  5. Problem says max/min and sorting helps?Strong hint: Sort + Greedy

Go Activity Selection Template (Sort by End)

Standard Greedy Activity Selection in Go

import (
    "math"
    "sort"
)

func maxActivities(intervals [][]int) int {
    // 1. Sort by END time
    sort.Slice(intervals, func(i, j int) bool {
        return intervals[i][1] < intervals[j][1]
    })

    lastEnd := math.MinInt
    count := 0

    // 2. Pick activity that finishes earliest
    for _, interval := range intervals {
        if interval[0] >= lastEnd {
            count++
            lastEnd = interval[1]
        }
    }
    return count
}

👉 Total Time: O(N log N) | Space: O(1)

Greedy Proof & Coin Change Counterexample

A local best choice does NOT automatically mean global optimal! Consider making amount 6 using coins [1, 3, 4]:

❌ Greedy Choice (Take largest coin first)

Take 4 $\to$ Remainder 2 $\to$ Take 1 + 1. Total = 3 coins (4 + 1 + 1).

✅ Optimal Choice (Dynamic Programming)

Take 3 + 3. Total = 2 coins (3 + 3). Greedy fails!

👉 Exchange Argument Rule: Explain WHY choosing the local best now will not hurt future options!

Greedy vs Backtracking vs Dynamic Programming

Greedy

Pick local best NOW, commit permanently, NO UNDO. Fast O(N) or O(N log N).

Backtracking

Try choice, explore recursively, UNDO (backtrack) if it fails. Exponential time.

Dynamic Programming

Compare choices across OVERLAPPING SUBPROBLEMS when local choices are unsafe.

Visual Memory Rule
Best Choice NOW  →  Commit Permanently  →  Never Undo Choice
Jump Game        →  Track farthest reach = max(farthest, i + nums[i])
Gas Station      →  Skip failed segment 0..i -> start = i + 1
Activity Selection → Sort by END time (earliest finish leaves max space)

💡 Golden Rule: "Make the choice that leaves the future with the best possible options."

Common Interview Mistakes

1. Assuming Greedy Always Works

Using greedy on problems where local choices hurt future options (like 0/1 Knapsack or Unbounded Coin Change).

2. Sorting by Start Instead of End

Sorting by start time for Non-overlapping Intervals. Greedy selection requires sorting by END time.

3. Overcomplicating with Heavy DP

Writing an O(N²) DP solution for Jump Game or Gas Station when a simple O(N) Greedy pass exists!

4. Saying "Greedy Because I Take the Biggest"

Vague explanations in interviews. Always state why taking the earliest finishing or highest unit item leaves the future no worse!

Interview Rules

  1. 1. Best local choice each step? → Consider Greedy Algorithm
  2. 2. Sorting reveals order? → Sort by end time, cost, profit, or weight first
  3. 3. Intervals + max count? → Sort by END time (earliest finish)
  4. 4. Farthest reachability? → Jump Game (farthest = max(farthest, i + nums[i]))
  5. 5. Minimum removals? → Maximize kept items (removals = N - kept)
  6. 6. Dynamic best choice needed? → Greedy + Priority Queue (Min/Max Heap)
  7. 7. Need undoing choices? → Use Backtracking instead of pure Greedy
  8. 8. Overall Complexity → Typically O(N) or O(N log N)

Small Rules

  1. Rule 1: Greedy commits immediately without undoing choices.
  2. Rule 2: Sorting data first often reveals the optimal greedy ordering.
  3. Rule 3: Explain WHY taking a choice cannot hurt future choices (Exchange Argument).
  4. Rule 4: Transform problems (e.g. minimum removals = total - maximum non-overlapping kept).
  5. Rule 5: Combine Greedy with Heaps when best candidates change dynamically (e.g. IPO, Refueling Stops).

Production Thinking

Earliest Deadline First SchedulerSchedule real-time OS background tasks by nearest deadline ASC

Resource Capacity AllocationAllocate smallest available worker pool node that satisfies request requirements

Network Routing (Dijkstra)Greedily pick currently closest unvisited node (works for non-negative edge weights)

Batch Job ProcessingProcess highest unit value or smallest duration jobs first to maximize throughput

Remember This

Greedy               → Best choice NOW
Usually              → No undo
Intervals            → Earliest end
Jump Game            → Farthest reach
Dynamic best choice  → Heap
Need ordering        → Sort first
Local best           ≠ always global best
Must explain         → Why choice is safe

💡 Golden Rule: "Make the choice that leaves the future with the best possible options."