Skip to content
Tech Interview Prep
Technical interview guide

Greedy Algorithms

Making the locally-best choice at each step and never revisiting it: correct only when the problem has the right structural guarantee.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with sorting and priority-queue behaviour cited from CPython 3.14.

Overview

Curated: · Written: · Reviewed:

Greedy Algorithms

In one line

Greedy takes the locally best choice at each step and never revisits it. It is correct only when an exchange argument shows that choice belongs to some optimal solution. Reach for it when one sort order makes each choice provably safe, and prove that order before writing code.

Key definitions

  • Greedy-choice property: the first choice is safe without solving the subproblems it creates.
  • Optimal substructure: an optimum contains optimal solutions to its subproblems. Dynamic programming needs it; greedy also needs the choice to be safe.
  • Exchange argument: take any optimum, find the first point where it differs from the greedy choice, swap the greedy choice in, and show the result is feasible and no worse.
  • Cut property: the lightest edge crossing any cut belongs to some minimum spanning tree.
  • Competitive ratio: an online algorithm's cost divided by the offline optimum's cost, in the worst case.
  • Canonical coin system: a denomination set for which greedy change is always optimal.

Formulas and complexity

Tsort-then-scan=O(nlog⁡n)+O(n)=O(nlog⁡n)T_{\text{sort-then-scan}} = O(n \log n) + O(n) = O(n \log n) Clist≤(2−1m)COPT(greedy list scheduling on m machines)C_{\text{list}} \le \left(2 - \tfrac{1}{m}\right) C_{\text{OPT}} \quad \text{(greedy list scheduling on } m \text{ machines)} Greedy set cover: ln⁡n-approximate\text{Greedy set cover: } \ln n\text{-approximate}

How it works

  1. Sort the items by the rule's key. The key is the whole design decision.
  2. Scan once, taking each item that is feasible under the constraint.
  3. Prove the first choice lies in some optimum (exchange argument), then induct on the remainder.
  4. A wrong greedy rule still returns a valid answer, so validity checks cannot catch it. Compare against brute force on small instances.
yes no Sort by rule key Scan items in order Feasible now? Take item Exchange argument: choice lies in some optimum

When to use and when not to

SituationGreedy?Reason
Max non-overlapping intervals, earliest finishYesExchange argument holds
Fractional knapsack, highest densityYesDivisibility makes density safe
Zero-one knapsackNoIndivisible items leave remainders; use DP
Coin change with {1, 3, 4}NoNot canonical; use DP
Huffman, MST, Dijkstra with non-negative weightsYesMerge rule, cut property, non-negativity
NP-hard covering problemsApproximation onlyThe ratio is the guarantee
Online schedulingYes, judged by competitive ratioOffline optimum is unknown at decision time
Rule depends on state that changes during the runUse a heap, not a sortA pre-sorted order applies a stale rule

Traps interviewers probe

  1. Trusting a rule because it passed the examples. Fix: hunt counterexamples with brute force on small random inputs, then supply an exchange argument. A clean run does not prove anything.
  2. Exchanging without checking feasibility. For A=[0,3], B=[2,5], C=[4,6], D=[5,8], the earliest-finish greedy gives {A, C}, and an optimum is {B, D}. Swapping A in for D gives {A, B}, which overlaps, so the proof fails. The valid exchange replaces B, the first-finishing interval of the optimum, with A, giving {A, D}, which is feasible.
  3. Using density greedy for zero-one knapsack. With A(60, 10), B(100, 20), C(120, 30) and capacity 50, density greedy returns 160 (A+B). The optimum is 220 (B+C). Fix: dynamic programming.
  4. Assuming a coin system is canonical. With {1, 3, 4} and amount 6, greedy gives 4+1+1 (three coins) while 3+3 uses two. Checking only amounts 1 to 5 hides this. Fix: use DP unless canonicity is established for the system.
  5. Dijkstra with a negative edge. Finalising a vertex early is safe only with non-negative weights. Fix: state the assumption, and use Bellman-Ford when negative edges exist.

Interview tips

Opening: "Greedy is correct here because an exchange argument puts the earliest-finishing interval in some optimum. The sort key is finish time."

Expected follow-ups:

  • Why is earliest finish safe and earliest start not?
  • When does density fail, and what changes when items are indivisible?
  • Is the setting online or offline, and what is the competitive ratio?
  • How would you test the rule before shipping it?

30-second outline:

  1. State the claim and the sort key.
  2. Give the three-step exchange argument.
  3. Name the counterexample that defeats the nearest alternative key.
  4. Quote O(n log n), and say you checked the rule against brute force on small instances.

Feedback on this overview

Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.