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.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-17

How do you prove that a greedy strategy is optimal, and what exchange argument technique is standardly used?

Answer

To prove a greedy strategy is optimal, you must establish two mathematical properties: optimal substructure (an optimal solution to the subproblem extends to an optimal solution to the whole problem) and the greedy-choice property (a globally optimal solution can be reached by making locally optimal choices without backtracking).

The standard technique to establish the greedy-choice property is an exchange argument. Rather than proving directly that the greedy choices are unique, you show that any hypothetical optimal solution $O$ that differs from the greedy solution $G$ can be transformed into another valid optimal solution $O'$ that shares one more greedy choice, without worsening the objective function.

The 4-step exchange argument recipe:

  1. State a hypothetical optimal solution $O = {o_1, o_2, \dots, o_k}$ and the greedy solution $G = {g_1, g_2, \dots, g_m}$. Assume without loss of generality that $O \neq G$.
  2. Identify the first point of divergence: the lowest index or step $i$ where $g_i \notin O$ (or where the choices differ).
  3. Define an exchange: swap an element $o_j \in O \setminus G$ with $g_i$ to form a candidate solution $O' = (O \setminus {o_j}) \cup {g_i}$.
  4. Prove validity and non-decreasing quality: show $O'$ satisfies all constraints (e.g. non-overlapping intervals, capacity, acyclicity) and that $\text{cost}(O') \le \text{cost}(O)$ (for minimization) or $\text{value}(O') \ge \text{value}(O)$ (for maximization). By induction, repeated exchanges transform $O$ into $G$ through a chain of optimal solutions, proving $|G| = |O|$ or $\text{value}(G) = \text{value}(O)$.
Python
# Concrete example: Interval Scheduling (earliest finish time)
# Given intervals: (start, finish)
intervals = [(1, 4), (3, 5), (0, 6), (5, 7), (3, 8), (5, 9), (6, 10), (8, 11)]
# Greedy choice: pick interval with earliest finish compatible with current end.
# G = [g_1, g_2, ...], O = [o_1, o_2, ...], sorted by finish times.
# First divergence at step r: g_r != o_r.
# By greedy selection: finish(g_r) <= finish(o_r).
# Replacing o_r with g_r cannot conflict with o_{r+1} because:
# finish(g_r) <= finish(o_r) <= start(o_{r+1}).
# Thus O' = (O - {o_r}) U {g_r} is valid and |O'| = |O|.
TechniqueHow it proves optimalityPrimary failure mode
Exchange ArgumentGradually transforms arbitrary optimal $O$ to greedy $G$ preserving feasibility and costChoosing an exchange that violates downstream constraints
Greedy Stays AheadMeasures a metric $M(i)$ at step $i$ and proves $M(G_i) \ge M(O_i)$ by inductionMetric is ahead locally but dead-ends before global completion
Matroid TheoryProves the constraint system forms an independent set system with exchange axiomsAssuming submodular/matroid structure on problems that are NP-hard (e.g., 0/1 knapsack)

Failure modes occur when engineers assume locally superior margins guarantee feasible extensions. For example, in 0/1 knapsack, sorting by value-to-weight density breaks because discrete granularity prevents full capacity utilisation; the exchange $o_j \to g_i$ leaves residual capacity that cannot be filled, failing step 4.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through the exchange argument, including where engineers most often get it wrong.

Answer

The 90-second answer. An exchange argument proves a greedy algorithm optimal by showing any optimal solution can be edited, one decision at a time, into the greedy solution without ever getting worse. Four steps: take an arbitrary optimum OPT; find the first place it disagrees with greedy; swap in the greedy choice and prove the result is still feasible and no smaller; conclude some optimum contains the greedy choice, then induct on the remaining subproblem. The step engineers skip is feasibility: you must show the rest of OPT still fits after the swap.

Worked example: interval scheduling. Maximize the number of non-overlapping intervals; greedy picks the earliest-finishing interval, then recurses on intervals starting after it. Intervals: A=[0,2), B=[1,3), C=[2,4), D=[3,5).

Greedy: A (finish 2), then C (finish 4) → {A, C}, size 2. OPT: {B, D}, size 2.

Exchange: OPT = {B, D}. The earliest-finishing interval in OPT is B, f(B)=3. Greedy's g = A, f(A)=2 ≤ 3. Replace B with A → {A, D}. Feasible? D starts at 3 ≥ f(A)=2, so yes. Same size. So an optimum containing A exists; recurse on intervals starting ≥ 2, where greedy picks C. Done.

The load-bearing fact is f(g) ≤ f(x): because g finishes no later than the interval it replaces, every interval that came after x still comes after g. Swap in something that finishes later and the rest can collide.

Where it goes wrong.

  1. Proving greedy is "good" without comparing to an arbitrary optimum. Showing your solution has size 2 proves nothing unless you show no solution has size 3.
  2. Skipping the feasibility check. The exchange is valid only because of the finish-time ordering; state it.
  3. Forgetting the induction. The exchange gives one optimum containing g; you still argue the residual problem is the same problem on a smaller input.
  4. Applying it to a variant where it is false. Weighted interval scheduling: A=[0,2) w=1, B=[1,3) w=100, C=[2,4) w=1. Greedy by finish picks A then C, weight 2; OPT is B, weight 100. The exchange fails at the value step: replacing B with A loses 99. Earliest-finish is optimal for cardinality, not for weight.

Huffman is the other common one. The exchange swaps the two least-frequent symbols with two deepest sibling leaves. Swapping a symbol of frequency f with a leaf of frequency f' ≥ f at depth d' ≥ d changes the cost by (f − f')(d' − d) ≤ 0, so it never increases.

Choosing the technique.

TechniqueProvesUse when
Exchangegreedy optimala local swap preserves feasibility
Induction on stepsgreedy optimalthe residual is the same problem
Adversary / counterexamplegreedy not optimalyou suspect a variant breaks it
Matroid / LP dualitygreedy optimalthe structure is a matroid (MST, scheduling)

Failure modes and detection. The classic silent failure is a greedy that is optimal on the tested distribution and wrong on a corner case: detect it by constructing the smallest counterexample where the exchange's feasibility step breaks, not by more random tests. If you cannot state why the swap preserves feasibility, you do not have a proof; you have a hope.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Explain what makes a greedy algorithm correct and how it changes a production decision.

Answer

The 90-second answer. Greedy is correct when two properties hold: the greedy-choice property, some globally optimal solution contains the locally optimal first choice, and optimal substructure. After committing to that choice, what remains is the same problem on a smaller input. The standard proof is an exchange argument: take an optimal solution that disagrees with the greedy choice, swap in the greedy choice, and show the objective does not get worse. If you cannot write that swap down, you have a heuristic, not an algorithm, and the difference shows up in production as a tail of inputs where it silently returns a suboptimal answer.

The clean sufficient condition is a matroid: if the feasible sets form a matroid and the objective is additive, greedy by weight is optimal (Rado–Edmonds). Minimum spanning tree (graphic matroid) and scheduling unit jobs by deadline to maximise on-time jobs (transversal matroid) are the textbook cases. Interval scheduling and Huffman coding are also optimal, but each needs its own exchange argument: they are not matroids.

Exchange argument, spelled out. For unweighted interval scheduling, greedy picks the interval that finishes earliest.

Claim: some optimal solution contains f, the earliest-finishing interval.
Proof: let OPT be optimal. If f is in OPT, done. Otherwise let g be the
interval in OPT with the earliest finish. f finishes no later than g, so
replacing g with f leaves every other interval in OPT compatible (they all
start at or after g's finish, which is at or after f's finish). |OPT| is
unchanged, so an optimal solution contains f.

Three lines, and checkable.

Where it changes a production decision. A CI scheduler on a single runner: jobs have a start and end time, run one at a time, and you want to maximise jobs completed. Earliest-finish greedy is optimal here. On a synthetic 40-job day it schedules 23 jobs; an ILP solver on the same input also returns 23. Greedy is O(n log n), the ILP takes seconds. Ship the greedy.

Now add weights: each job carries a priority value and you want to maximise total priority, not job count. Same greedy, same code path:

A = [0, 2)  weight 1
B = [1, 3)  weight 10
C = [3, 5)  weight 10

Greedy (earliest finish): A finishes at 2, then C starts at 3.
  -> A + C, total weight 11.
Optimal: B + C, total weight 20.

Greedy returns 11 where 20 was available: a 45% shortfall on this input, and it never errors, never logs, just schedules the wrong jobs. On the 40-job day above, greedy picks 23 jobs worth 410 priority units; the DP picks 19 jobs worth 780. Fewer jobs, nearly double the value. That is the decision: if the objective is throughput, greedy is correct and fast; if it is weighted value, greedy is wrong and you need the O(n log n) DP over intervals sorted by finish time.

Failure modes and detection. The failure is silent and input-dependent: greedy passes every hand-picked example and fails on a specific shape. Here, a short low-weight interval that blocks two high-weight ones. Detect it by (a) writing the exchange argument before the code, and stopping if the swap does not go through; (b) differential testing against an ILP or DP oracle on random inputs; (c) logging the objective value per run, so a regression in realised value is visible even when the job count looks fine.

When not to use it. No exchange argument, no matroid, or a non-additive objective: minimising makespan on two machines, where LPT is a constant-factor approximation, not optimal. Then reach for DP, ILP, or an approximation with a stated bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you explain greedy with a heap without using the usual slogan?

Answer

The 90-second version. Greedy with a heap is what you reach for when the greedy choice is "the best option right now" and what counts as best changes as you consume options. A sort fixes an order once; a heap re-derives the current maximum in O(log k) after each update, where k is the number of live candidates. If the ranking is static (activity selection by end time, Huffman's two smallest) sort once, O(n log n), then walk it. If the ranking depends on state you mutate as you go, the sort is answering a question that has already changed.

Mechanism. Build the heap with heapify, O(k), not k separate pushes. Each step: pop the current best, O(log k); mutate the state; push the updated candidate back, O(log k). Over n steps that is O(n log k). The alternative, re-sorting the candidate set every step, is O(n log n) per step, O(n² log n) total.

Worked trace. Task scheduler, cooldown 2, tasks AAABBB. Greedy rule: always run the most frequent task that is not cooling down. Max-heap of remaining counts, plus a queue of (remaining, ready_time).

theap (max)popready queue afterpush back
1A3, B3A→2(2,3)—
2B3B→2(2,3),(2,4)—
3——(2,4)A2
4A2, B2A→1(2,4),(1,6)B2
5B2B→1(1,6),(1,7)—
6——(1,7)A1
7A1, B1A→0(1,7)B1
8B1B→0——

Result 8. The lower bound (maxFreq−1)(cooldown+1) + numMaxFreq = (3−1)(3) + 2 = 8, so the greedy is optimal here.

Code.

Python
import heapq
from collections import deque

def least_interval(tasks, cooldown):
    counts = {}
    for t in tasks:
        counts[t] = counts.get(t, 0) + 1
    heap = [-c for c in counts.values()]
    heapq.heapify(heap)          # O(k), k = distinct tasks
    ready = deque()              # (remaining, time it may re-enter)
    time = 0
    while heap or ready:
        time += 1
        if heap:
            remaining = -heapq.heappop(heap) - 1
            if remaining:
                ready.append((remaining, time + cooldown))
        if ready and ready[0][1] == time:
            heapq.heappush(heap, -ready.popleft()[0])
    return time

print(least_interval("AAABBB", 2))   # 8

Trade-offs.

sort onceheap
setupO(n log n)O(k) heapify
per stepO(1)O(log k) pop + O(log k) push
totalO(n log n)O(n log k)
valid whenranking is staticranking depends on mutated state

When the ranking is static, the sort wins on constant factor and simplicity: do not reach for a heap. When k is small and fixed (say, top-3 of a stream), a heap is O(log 3) per item and a sort is not even an option because the stream does not end.

Failure modes. Pre-sorting when the rule depends on evolving state applies a stale rule; the schedule is wrong but plausible. Detect it by differential testing against a brute-force simulator on small random inputs, and by checking the result against the lower bound above: a greedy that beats the bound is buggy, one that misses it is suboptimal. A second failure: forgetting to re-push a candidate whose count is still positive, which silently drops work and shortens the schedule.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does finding counterexamples force that a junior answer usually skips?

Answer

The trade-off is between two things that look interchangeable and aren't: counterexample search is cheap, automatable, and only ever refutes; a correctness proof is expensive, manual, and is the only thing that confirms. The common shortcut is to treat a clean random test run as if it bought the second, and it doesn't: no number of passing trials converts "I haven't found a counterexample" into "there isn't one."

Concretely, take the interval-scheduling rule "pick the interval with the earliest start time." Three intervals kill it:

[0,10], [1,2], [3,4]

Earliest-start takes [0,10], and then nothing else fits, for 1 interval. The optimum is [1,2] and [3,4], for 2. Brute force over the 2^3 = 8 subsets finds this on the first trial; the counterexample is three intervals wide, not a stress-test-scale input.

That's the mechanism behind the trade-off. The counterexample is tiny, so search finds it fast, but the input space is exponential in the number of intervals, so any sampling scheme covers a vanishing fraction of it. You are trading coverage for tractability, and the region you didn't sample is exactly where the next bug lives. The failure mode is specific: a 20,000-instance run that passes gets read as evidence of correctness, when it is evidence about the distribution you sampled from. Bugs that survive it are structural, a particular ordering or tie-breaking case, not large, so scaling the test up doesn't reach them.

So the trade-off forces a decision per rule, not a general policy. Use search to refute: it's seconds of compute and the fastest way to kill a wrong rule. Use an exchange argument to confirm: it's the only thing that covers every input, and it's why earliest-finish-time is correct where earliest-start isn't. You show that swapping the first chosen interval for the earliest-finishing one never reduces the count, so the greedy choice is safe to commit to. Pay for the proof when the rule's correctness is semantic, when a wrong answer is a wrong answer. Reach for measurement instead when the decision turns on cost rather than correctness, because there the number you need is a latency or a dollar figure, and no proof produces it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does interval scheduling guarantee, and what does it deliberately leave open?

Answer

The guarantee. For a single machine and the unweighted objective "accept the most intervals," earliest-finish-first is exactly optimal: it returns a maximum-cardinality set of pairwise non-overlapping intervals. Not approximate, not a heuristic. Sort by finish time, scan once, accept an interval whenever it starts at or after the last accepted finish. O(n log n) for the sort, O(n) for the scan.

Why it holds: exchange argument. Let G be greedy's set and O an optimal set, both ordered by finish. Greedy's first interval finishes no later than O's first, so swapping O's first for greedy's keeps O feasible and the same size. Induct. Finishing earliest leaves the most room, so it never costs you a slot.

Python
# Python 3.12
def max_non_overlapping(intervals):
    intervals.sort(key=lambda x: x[1])   # earliest finish first
    count, last_end = 0, float("-inf")
    for s, e in intervals:
        if s >= last_end:                # touching counts as compatible
            count += 1
            last_end = e
    return count

Trace on [(0,10), (1,2), (3,4)], sorted by finish to [(1,2), (3,4), (0,10)]:

intervals >= last_end?countlast_end
(1,2)1 >= -inf yes12
(3,4)3 >= 2 yes24
(0,10)0 >= 4 no24

Result 2. Sorting the same input by start gives 1: (0,10) is taken first and blocks both others. Sorting by duration fails on [(0,10), (9,11), (10,20)]: shortest-first takes (9,11), which straddles the gap and blocks (0,10) and (10,20), giving 1 where the optimum is 2.

What it leaves open. The guarantee is bounded to that exact problem. Change any of the following and earliest-finish stops being optimal:

  • Objective. Maximum count is not maximum covered time. Earliest-finish maximizes the number of intervals; maximizing total busy time or utilization is a different problem and greedy fails on it.
  • Weights. If each interval carries a value, earliest-finish is not optimal. Weighted interval scheduling is a DP: sort by finish, let p[j] be the last interval finishing at or before start_j (binary search), then OPT[j] = max(OPT[j-1], w_j + OPT[p[j]]), O(n log n).
  • Machines. k identical machines is interval partitioning, i.e. interval graph coloring. The minimum number of machines equals the maximum overlap depth; the greedy is by start time with a min-heap of finish times, not earliest-finish.
  • Online arrival. If intervals arrive over time and you accept or reject irrevocably, no deterministic algorithm beats competitive ratio 1/2, and earliest-finish achieves it.
  • Endpoint convention. The scan uses s >= last_end, so touching intervals [a,b] and [b,c] are compatible. If your problem defines touching as overlap, the comparison becomes s > last_end and the accepted set changes.

Failure modes. The rule is correct but easy to misapply. Sorting by start or by duration both look plausible and both pass casual testing, because the counterexamples are small and specific: a single three-interval input defeats each, as above. The other silent failure is the objective: a team that wants to maximize machine utilization but reaches for earliest-finish gets maximum count and a worse schedule, and nothing in the output flags it. Detect it by stating the objective before choosing the rule, and by checking the endpoint convention against the input format. When the decision turns on weighted value, machine count, or online arrival, the answer is a different algorithm, not a tweak to this one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How do you solve the interval scheduling problem greedily, and why does sorting by end time succeed where sorting by start time fails?

Answer

To maximize the number of non-overlapping intervals (or to minimize removals), sort all intervals by end time in ascending order, select the first interval, and greedily take each subsequent interval whose start time is greater than or equal to the end time of the previously selected interval.

Why Earliest End Time Works (The Mechanism)

The greedy choice property holds because picking the interval that finishes earliest frees up the resource as soon as possible, leaving the maximum remaining time available for subsequent choices.

By mathematical exchange argument: let $O = [o_1, o_2, \dots, o_k]$ be an optimal subset of disjoint intervals ordered by end time, and let $g_1$ be the interval with the earliest finish time among all eligible candidates. Because $g_1$ ends no later than $o_1$ ($g_1.\text{end} \le o_1.\text{end}$), replacing $o_1$ with $g_1$ cannot conflict with $o_2, \dots, o_k$. Thus, an optimal schedule containing the greedy choice always exists. Inducting on the remaining timeline proves that every subsequent greedy pick preserves optimality.

Why Start Time Fails

Sorting by start time fails because choosing the earliest start time allows an arbitrarily long interval to monopolize the entire timeline and crowd out multiple smaller intervals.

StrategySelection CriterionCounterexample IntervalsChosen CountOptimal Count
Earliest StartMin start time[0, 100], [1, 2], [3, 4]1 ([0, 100])2 ([1, 2], [3, 4])
Shortest DurationMin (end - start)[0, 5], [4, 7], [6, 11]1 ([4, 7])2 ([0, 5], [6, 11])
Earliest EndMin end time[0, 100], [1, 2], [3, 4]2 ([1, 2], [3, 4])2 ([1, 2], [3, 4])

Implementation (Python 3)

Python
def max_non_overlapping_intervals(intervals: list[tuple[int, int]]) -> int:
    if not intervals:
        return 0
    # Sort by finish time in O(n log n)
    sorted_intervals = sorted(intervals, key=lambda x: x[1])

    count = 1
    last_end = sorted_intervals[0][1]

    for start, end in sorted_intervals[1:]:
        if start >= last_end:
            count += 1
            last_end = end

    return count

Complexity and Trade-offs

  • Time: $\mathcal{O}(n \log n)$ dominated entirely by the sorting step; the greedy linear scan runs in $\mathcal{O}(n)$.
  • Space: $\mathcal{O}(n)$ or $\mathcal{O}(1)$ auxiliary space depending on whether the sort is done in place.
  • Failure Modes: The single-resource earliest-end-time greedy choice breaks if intervals have weights or values (which requires dynamic programming in $\mathcal{O}(n \log n)$ with binary search), or if intervals can wrap around a cyclic buffer (requiring two-pass unwrapping).

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe interval partitioning and the evidence you would collect before relying on it.

Answer

Interval partitioning asks for the fewest resources such that no two overlapping intervals share one. The answer is the peak depth: the maximum number of intervals overlapping at any single instant. Sort by start time, keep a min-heap of the end time of the last interval in each open resource, and reuse the earliest-freed resource whenever it is free at the new interval's start.

Before relying on it I want three pieces of evidence: that the data really is a set of intervals on one clock, the distribution of peak depth on production data rather than its mean, and the fraction of events that share a timestamp, because the tie-break rule at equal times decides the number.

Why the bound is tight

Lower bound: at the instant of maximum overlap, k intervals all contain that instant, so they pairwise overlap and need k distinct resources. Upper bound: when the greedy opens a new resource for interval i, every existing resource is busy, so each holds an interval containing start(i). Those intervals all contain start(i), hence pairwise overlap, so the depth there is at least k+1. Greedy never opens more than the peak depth and cannot open fewer. The argument only uses "busy at start(i)", so it holds even when intervals arrive out of order; sorting is for the heap's efficiency, not for correctness.

Code

Python
import heapq

def partition(intervals):
    """intervals: (start, end) half-open [start, end). Returns rooms used."""
    rooms = []                      # min-heap of the end time of each room's last interval
    for s, e in sorted(intervals):
        if rooms and rooms[0] <= s:
            heapq.heapreplace(rooms, e)   # earliest-freed room is free at s
        else:
            heapq.heappush(rooms, e)      # every room busy -> open one
    return len(rooms)

Trace on A[9:00,10:00), B[9:30,10:30), C[10:00,11:00), D[10:15,10:45):

intervalheap beforedecisionheap after
A[]push 10:00[10:00]
B[10:00]10:00 > 9:30, push 10:30[10:00, 10:30]
C[10:00, 10:30]10:00 <= 10:00, replace[10:30, 11:00]
D[10:30, 11:00]10:30 > 10:15, push 10:45[10:30, 10:45, 11:00]

Three rooms. Peak depth agrees: at 10:15, B, C and D are all active.

The tie-break is the answer

[9:00,10:00) and [10:00,11:00) need one room. Treat them as closed and the sweep at 10:00 sees the start before the end and reports two. In Python, events.sort() on (time, delta) tuples puts -1 before +1 at equal times, which is the half-open rule for free:

Python
def peak_depth(intervals):
    events = [(s, 1) for s, e in intervals] + [(e, -1) for s, e in intervals]
    events.sort()          # at equal time, -1 sorts before +1
    cur = peak = 0
    for _, d in events:
        cur += d
        peak = max(peak, cur)
    return peak

Alternatives

ApproachTimeSpaceAssignment?Use when
Sweep over sorted eventsO(n log n)O(n) for 2n eventsnoyou only need the count
Sort + min-heap greedyO(n log n)O(k), k = peak depthyesyou need the room assignment
Difference array over bucketed timeO(n + T)O(T)nothe time domain is bounded and coarse: 1440 minute buckets per day

The deciding questions are whether you need the assignment and whether the time domain is bounded. With minute-granularity bookings over a day, bucketing beats the sort; with arbitrary timestamps it does not.

Evidence and failure modes

  • Model: half-open or closed? Zero-length or negative intervals? One clock domain: wall-clock timestamps that NTP can step will reorder events.
  • Depth distribution: p50, p99 and max over a real day. The resource count is the max, so the tail sizes the fleet; a mean of 3 with a max of 120 is a 120-room problem.
  • Timestamp collisions: what fraction of the 2n events share a time with another? If it is large, the tie-break rule is deciding your number.
  • Cost split: profile the sort against the heap pass. On a 10^6-interval input the sort is essentially the whole cost (order of a second in CPython 3.12; hypothetical, measure yours).
  • Cross-check: run an O(n²) pairwise overlap count on a 10^4 sample and compare.

The identity fails outside interval graphs. Peak overlap equals the chromatic number only because interval graphs are perfect; add a constraint that two non-overlapping intervals still cannot share a resource and max clique becomes a lower bound, not the answer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach the jump-game reachability rule to an engineer who has only seen it as a rule of thumb.

Answer

The rule is a frontier argument, not a search. Sweep left to right keeping reach, the largest index any jump seen so far can land on. If you ever stand at an index past reach, nothing to your left can carry you there, and nothing further right is reachable either.

The invariant. After processing index i, reach = max over 0 <= j <= i of (j + a[j]), and every index in [0, reach] is reachable from 0.

  • Base: at i = 0, reach = a[0], and indices 0..a[0] are one jump away.
  • Step: if i <= reach, then i is reachable, so from i you can land anywhere in [i, i + a[i]], extending the reachable prefix to max(reach, i + a[i]). If i > reach, then j + a[j] < i for every j < i, so no jump from the processed prefix lands at or beyond i: index i and everything after it are unreachable.

That is the whole correctness argument, and it is why greedy never has to choose a jump: reach is the maximum over all choices, not one of them, so no reachable position is ever discarded.

Trace. [2, 3, 1, 1, 4]:

ia[i]reach beforei > reach?reach after
020no2
132no4
214no4
314no4
444no8

Returns True. [3, 2, 1, 0, 4]:

ia[i]reach beforei > reach?reach after
030no3
123no3
213no3
303no3
443yes—

Returns False: the zero at index 3 caps the frontier at 3, so index 4 is never entered.

Python
# Python 3
def can_reach(a):
    reach = 0
    for i, jump in enumerate(a):
        if i > reach:
            return False
        reach = max(reach, i + jump)
    return True

Cost. One pass, O(n) time, O(1) space. The dynamic program dp[i] = any(dp[j] and j + a[j] >= i for j < i) is O(n^2) time and O(n) space; it computes the same predicate, but the greedy collapses it because reach is monotone and the any over j is exactly i <= reach. Brute force over jump sequences is exponential and is never the right answer here.

Where it breaks.

  • Off-by-one on the comparison: i >= reach wrongly rejects the case i == reach, which is reachable. You can land exactly on the frontier. The check is i > reach.
  • a[0] == 0 with n > 1: reach stays 0, i = 1 > 0, returns False. Correct, and worth stating because it is the smallest failing input.
  • Empty array: the loop body never runs and it returns True. Whether that is right depends on your definition of "already at the end"; pin it down before writing the function.
  • Reachability is not minimum jumps. The greedy above answers only yes/no. Minimum jumps needs a second frontier: track cur_end (end of the current jump's range) and farthest; when i == cur_end, increment the jump count and set cur_end = farthest. Reusing the reachability loop for the counting problem is the common mistake.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Given an array where each element is the maximum jump length from that position, what is the minimum number of jumps to reach the last index?

Answer

Two variables carry the algorithm: cur_end is where the current jump's window stops, and farthest is the furthest index reachable from any position inside that window. Walk i from 0 to n-2 pushing farthest = max(farthest, i + nums[i]). Every time the walk reaches cur_end, the window is exhausted: spend a jump, slide cur_end to farthest. O(n) time because each index is scanned once, O(1) extra space.

Python
def min_jumps(nums: list[int]) -> int:
    n = len(nums)
    if n <= 1:
        return 0
    jumps, cur_end, farthest = 0, 0, 0
    for i in range(n - 1):
        farthest = max(farthest, i + nums[i])
        if i == cur_end:
            if farthest == cur_end:        # window cannot advance
                return -1
            jumps += 1
            cur_end = farthest
            if cur_end >= n - 1:
                break
    return jumps if cur_end >= n - 1 else -1

Trace on [2, 3, 1, 1, 4]:

ifarthesti == cur_endaction
02yesjumps=1, cur_end=2
14no—
24yesjumps=2, cur_end=4, break

Answer: 2, via 0 → 1 → 4.

Why optimal, not just plausible: read the array as a graph where i has an edge to every j in [i+1, i+nums[i]]. Minimum jumps is shortest path in an unweighted digraph, so BFS gives it, and every BFS level is exactly one jump. The window [prev_end, cur_end] is the current BFS layer; scanning that window and taking the max reach is the layer expansion done in place. Because each index is scanned once, the jump count equals BFS depth without materialising the O(n²) edge set. If a layer's max reach does not push past cur_end, there is no next layer and the target is unreachable.

Contrast with the DP formulation: dp[i] = min over j < i with j+nums[j] >= i of dp[j]+1, dp[0] = 0. Correct, but O(n²) time and O(n) space because it rescans every earlier index for each i. It is the right shape when jump cost is not uniform or when you need the actual path with back-pointers; for a uniform count the greedy wins outright. The reachability-only variant (jump game I) collapses to one farthest and a single comparison to n-1: the counting variant needs the window boundary and a counter layered on top, because farthest alone cannot tell you how many jumps were used.

Edge cases worth naming:

  • n == 1 returns 0. The range(n-1) loop bound makes this fall out naturally.
  • A zero that closes a window: [1, 0, 2, 0, 0] dies at index 1 because farthest == cur_end; return -1 rather than a wrong number.
  • An unreachable end must not return a stale jumps, hence the final cur_end >= n - 1 guard.
  • The n - 1 loop bound matters: running to n counts a spurious jump when i reaches the last index.

The failure this invites is specific: the algorithm silently assumes nums[i] >= 0. Negative "jumps" break the monotone-window invariant and the greedy is wrong: you need BFS or DP. Same story if cost per jump varies: greedy minimises the count of jumps, not their sum.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

How do you solve the Gas Station circular tour problem in O(N) time and O(1) space using a greedy approach?

Answer

Core answer

Clarify the setup: gas[i] is fuel available at station i, cost[i] is fuel to travel from i to i+1 (mod N). Return a starting index that completes the circuit, or -1. Assume gas[i], cost[i] >= 0 and N >= 1.

Two facts make a single-pass O(N) greedy work.

  1. Total feasibility. A tour exists iff sum(gas) >= sum(cost). If total gas is less than total cost, no start can succeed.
  2. Skip invariant. Suppose starting at A with an empty tank, the running tank first goes negative when trying to leave station B. Then no station k in [A, B] can reach B+1. At k, the tank from A was >= 0, so starting at k with 0 is no better. So we can skip A..B and set the candidate start to B+1.

We track total_surplus over the whole array and current_tank since the current candidate start. When current_tank drops below 0, reset the candidate start to i+1 and current_tank to 0. At the end, if total_surplus >= 0, the candidate start is valid; otherwise -1.

Python
def can_complete_circuit(gas: list[int], cost: list[int]) -> int:
    total_surplus = 0
    current_tank = 0
    start_idx = 0

    for i in range(len(gas)):
        net = gas[i] - cost[i]
        total_surplus += net
        current_tank += net

        if current_tank < 0:
            start_idx = i + 1
            current_tank = 0

    return start_idx if total_surplus >= 0 else -1

Trace

Consider gas = [1, 2, 3, 4, 5] and cost = [3, 4, 5, 1, 2], so Δ = [-2, -2, -2, +3, +3]:

Step iΔ[i]current_tankcurrent_tank < 0?Actionstart_idxtotal_surplus
0-2-2YesReset1-2
1-2-2YesReset2-4
2-2-2YesReset3-6
3+3+3NoAdvance3-3
4+3+6NoAdvance30

At loop termination, total_surplus is 0 >= 0, returning start_idx = 3. Check: start at 3, tank 0+4-1=3, then 3+5-2=6, then 6+1-3=4, then 4+2-4=2, then 2+3-5=0. Valid.

Why no second pass is needed

The candidate start is the index after the last time the running tank hit a new minimum. Equivalently, it is the index after the global minimum prefix sum of Δ (including the initial prefix sum 0). Every prefix sum from that point onward, wrapping around, is at least that minimum, so the tank never goes negative during the wrap. That is the rigorous reason the single pass suffices.

Edge cases and failure modes

  • Single station (N=1). gas[0] >= cost[0] returns 0; otherwise -1. The loop handles it: if net >= 0, start_idx stays 0 and total_surplus >= 0; if net < 0, start_idx becomes 1 and total_surplus < 0, so -1.
  • All deltas negative. total_surplus < 0, start_idx becomes N, and the final check returns -1. The total check prevents returning N.
  • Multiple valid starts. For gas = [2, 2], cost = [1, 1], both 0 and 1 complete the tour. The algorithm returns 0 (no reset). The problem accepts any valid start; LeetCode 134 guarantees uniqueness in its test cases, but the algorithm does not rely on it.
  • Integer overflow. In Java/C++, total_surplus and current_tank can overflow if the sum of |gas[i] - cost[i]| exceeds INT_MAX. For LeetCode constraints (n <= 10^5, gas[i], cost[i] <= 10^4), the maximum total is 10^9, which fits in a 32-bit signed int (2,147,483,647). For larger constraints, use long / int64_t. current_tank is reset to 0 on failure, so it never accumulates across resets, but it can still grow large within a single segment.
  • Empty input (N=0). Not in the problem constraints (n >= 1), but if N=0, the loop does not run and returns 0, which is invalid. Guard with if not gas: return -1 if needed.
  • Negative gas or cost. Not in the problem (both >= 0). If negative values were allowed, the skip invariant would not hold.

Complexity and alternatives

  • Brute force. Simulate from each station until failure: O(N^2) time in the worst case (e.g., failing at the last hop), O(1) space.
  • Prefix-sum / Kadane-style. Compute prefix sums P[i] = sum_{0}^{i-1} Δ, find the index of the global minimum, start there. This is O(N) time but requires O(N) space to store P, or two passes with O(1) space. The greedy above is one pass, O(1) auxiliary space.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

When does a greedy solution to knapsack work?

Answer

It turns on one question, and it is not about the algorithm: can you take part of an item?

Fractional knapsack (items divisible) is solved greedily on value-to-weight ratio: sort by density ρ_i = v_i/w_i, take items whole in that order until the next one does not fit, then take the fraction of it that does. 0/1 knapsack (items whole) is not; the same ordering loses, and the standard remedy is dynamic programming in O(nW) time over capacity: pseudo-polynomial in W.

Mechanically, the greedy-choice property holds for fractional because weight is tradeable. Let item 1 be the densest and let S be an optimal solution that leaves part of item 1 behind or carries some lighter-density item j. Move weight ε from j to item 1: the value changes by ε(ρ₁ − ρⱼ) ≥ 0, so S is never better than a solution that takes item 1 first. The residual capacity then leaves the same problem with smaller W, so the choice repeats. The exchange is only legal because ε may be a fraction: that is the entire boundary between the two problems.

The counterexample where the densest item wastes capacity: W = 6.

itemvalueweightvalue/weight
A641.50
B431.33
C431.33

Greedy takes A, leaving capacity 2, which neither B nor C fits into: value 6. Optimal takes B + C = 8 for weight 6. That shape is not exotic: it appears whenever one item's weight approaches capacity and leaves unusable slack.

The same instance under DP (Python 3, one-dimensional table over capacity):

Python
def knapsack_01(items, W):
    dp = [0] * (W + 1)
    for v, w in items:                       # (value, weight)
        for c in range(W, w - 1, -1):        # descending keeps each item single-use
            dp[c] = max(dp[c], dp[c - w] + v)
    return dp[W]

knapsack_01([(6, 4), (4, 3), (4, 3)], 6)     # 8

Cost is O(nW): 3 items × 7 capacities here, but 200 items with W = 10⁵ is 2×10⁷ inner steps. Fine. W = 10⁹ makes the table impossible, and that is exactly where you still need greedy, as a bound rather than an answer.

Telling which problem a real design presents: ask whether half an item is meaningful. Traffic shaping, budget allocation, filling a disk with log segments you can truncate: divisible, sort by density. Pods on a node, VMs in a cluster, features in a release: whole units, DP or better. Second question: is there exactly one capacity constraint? Density ordering needs one; add a second dimension (CPU and memory) and no single order is optimal: that is multiple knapsack and greedy degrades further.

Greedy still earns its place inside 0/1 solvers: the fractional optimum is the LP relaxation, a tight upper bound that branch-and-bound prunes with; the better of the density order and the single most valuable item is a 1/2-approximation; and scaling values down before running DP gives an FPTAS.

The failure this invites is specific: a density sort that survives testing because the test items are small, and dies when one item's weight nears capacity. Inject the table above as a unit test.

In practice, settle divisibility and the number of capacity constraints first, write that assumption into the design, then use O(nW) DP when W is small and the fractional bound when it is not.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does coin change and canonical systems matter, and where is it irrelevant?

Answer

Core answer. Coin change matters wherever a system pays out from a fixed set of denominations and you want the fewest coins: vending machines, ATM cassettes, cash-drawer logic, currency-conversion APIs. Greedy is correct exactly when that denomination set is canonical, when repeatedly taking the largest coin that fits always yields an optimal count. US coins {1, 5, 10, 25} are canonical. Plenty of real sets are not, and greedy gives no warning when it is wrong.

Where it is irrelevant: (1) if you solve with dynamic programming, which is correct for every denomination set, canonicity never enters the picture; (2) if the denominations vary per query rather than forming a fixed system, there is nothing to be canonical about; (3) in the counting-ways variant ("how many combinations sum to N"), greedy does not apply at all.

Mechanism. A set is canonical iff greedy is optimal for every target. That is a property of the denominations, not the algorithm. The classic counterexample:

{1, 3, 4}, target 6
greedy:  4 + 1 + 1 = 3 coins
optimal: 3 + 3     = 2 coins

Greedy commits to 4 because it is the largest coin ≤ 6, and that choice blocks the optimum. US coins never do this at any target.

Detection. Two ways. Cheap: run greedy and DP side by side over a range of targets and diff the counts. Any mismatch proves non-canonicity. Exact: canonicity is decidable in polynomial time; Kozen and Zaks gave an O(n³) test in the number of denominations. You do not need the exact test in an interview, but knowing it exists is the difference between "I think greedy is fine" and "greedy is provably fine here."

Cost. DP is O(amount × n) time, O(amount) space. Greedy is O(n log n) once, or O(n) with pre-sorted denominations. For amount = 10⁶ and n = 8, that is roughly 8×10⁶ DP steps versus a handful of greedy steps, which is exactly why production systems reach for greedy and then have to justify it.

Failure mode. Assuming greedy is safe because it is for dollars. It survives casual testing because most test targets are small and the counterexample sits at one specific target. Detect it by diffing greedy against DP on sampled targets, or by running the canonicity test once at build time and asserting the result.

In practice. Use DP unless the denomination set is known canonical, and write that assumption down where the code lives. If you do use greedy, pin it with a test that compares against DP over the target range you actually serve.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How does Huffman coding use greedy choice to build an optimal prefix-free code?

Answer

Huffman coding makes one greedy decision and repeats it: merge the two lowest-frequency subtrees. Everything else (prefix-freeness, optimality, the entropy bound) falls out of proving that single step safe.

Algorithm. One leaf per symbol, weighted by its frequency, in a min-heap keyed by weight. Repeatedly pop the two smallest weights and push their parent with weight equal to the sum. After n−1 merges one node remains, the root; reading 0 on a left edge and 1 on a right gives each symbol its codeword. Cost is O(n log n): n−1 merges, two pops and one push each at O(log n).

Python
import heapq  # Python 3.14

def huffman(freq):                      # freq: {symbol: count}
    heap = [(w, i, (s, None, None)) for i, (s, w) in enumerate(freq.items())]
    nxt = len(heap)
    heapq.heapify(heap)
    while len(heap) > 1:
        w1, _, l = heapq.heappop(heap)  # the two lowest frequencies
        w2, _, r = heapq.heappop(heap)
        heapq.heappush(heap, (w1 + w2, nxt, (None, l, r)))
        nxt += 1
    return heap[0][2]                   # root; walk it for the codes

The i counter is not decoration: it breaks ties on weight so the comparison never descends into the tree tuples. (Sorting the frequencies once and draining two queues (leaves in one, merged nodes in the other) is also O(n log n), dominated by the sort, and is what tight encoders do to avoid heap overhead.)

Why the greedy step is safe. Let a and b be the two smallest frequencies. Take an optimal tree and its two deepest-level siblings x and y; every binary tree with at least two leaves has such a pair. Swap a↔x and b↔y. Weighted path length changes by (f_x − f_a)(l_a − d) + (f_y − f_b)(l_b − d), where d is the deepest depth and l_a, l_b ≤ d are a's and b's old depths. Both terms are ≤ 0, so the swap costs nothing: there exists an optimal tree where the two smallest symbols are siblings at the deepest level. Merge them into one node of weight f_a + f_b and the problem shrinks to n−1 symbols; an optimal tree for the reduced instance is optimal for the original. Greedy choice plus optimal substructure, by induction on n.

Prefix-free and the entropy bound. All symbols live at leaves, so no codeword is a prefix of another and a decoder emits a symbol the moment it hits a leaf: no delimiters, no lookahead. Huffman minimises expected length over all prefix codes, and that length L satisfies H ≤ L < H + 1 bits per symbol.

Worked example. Frequencies a:45, b:13, c:12, d:16, e:9, f:5 (sum 100). Merges: 5+9=14, 12+13=25, 14+16=30, 25+30=55, 45+55=100.

symbolfreqcodelength
a4501
b131013
c121003
d161113
e911004
f511014

Expected length = (45·1 + 13·3 + 12·3 + 16·3 + 9·4 + 5·4)/100 = 224/100 = 2.24 bits/symbol. Entropy H ≈ 2.22, so Huffman sits 0.02 above the bound. Fixed-length needs ⌈log₂ 6⌉ = 3 bits/symbol: 34% more bits on this distribution.

Where it shows up, and the trap. Huffman trees are the data-compression workhorse (Algorithms 4th Edition builds one in its compression chapter); formats store only codeword lengths and both sides regenerate an identical canonical code, so the table stays small. The failure this invites is specific: assuming the merge is "obviously" right because merging small things looks cheap. The exchange argument is the whole claim to optimality, and it is what tells you when the rule breaks. It breaks when frequencies are unknown up front (you need two passes or an adaptive scheme), when costs are not additive (length-limited codes need package-merge or DP), or when you care about symbols in context. Huffman is optimal among prefix codes, not at the entropy bound: a symbol with p = 0.51 wants 0.971 bits and Huffman must give it 1, which is why arithmetic or ANS coding wins on such distributions. Ties change the tree's shape but never the weighted path length: recompute WPL if two encoders disagree. Handle n = 1 and empty input explicitly.

For interviews this is the standard "greedy plus proof" question: the follow-up is almost always the swap, or the variant where the merge rule stops being optimal.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How does Huffman coding construct an optimal prefix code using a greedy approach, and why does the greedy choice yield minimum weighted path length?

Answer

What a strong candidate says first

Huffman coding answers one question: given a static frequency table over an alphabet, what prefix-free binary code minimizes total encoded bits? The greedy rule is to repeatedly merge the two least-frequent nodes until one tree remains. It is optimal because of an exchange argument: the two rarest symbols can always be pushed to maximum depth without increasing cost: plus optimal substructure: merging them adds a constant to every candidate tree's cost, so minimizing the reduced problem minimizes the original. Assumptions: frequencies are known before encoding, one symbol per leaf, binary alphabet, no codeword-length cap. Drop any of those and plain Huffman stops being the right tool.

Mechanism

Min-heap of leaves keyed by frequency. In each of n−1 rounds, pop the two minima and push their parent with summed frequency. Edge labels 0/1 give the codewords. O(n log n) time, O(n) space.

Python
import heapq

def huffman_tree(freq: dict[str, int]):
    heap = [(w, i, sym) for i, (sym, w) in enumerate(freq.items())]
    heapq.heapify(heap)
    uid = len(heap)
    while len(heap) > 1:
        w1, _, left = heapq.heappop(heap)
        w2, _, right = heapq.heappop(heap)
        heapq.heappush(heap, (w1 + w2, uid, (left, right)))
        uid += 1
    return heap[0][2]

The unique uid is the tie-break. Without it, two nodes of equal weight with non-comparable payloads raise TypeError in Python 3, and even when it does not crash, non-deterministic tie-breaking means two runs on the same input produce different trees.

Trace: frequencies a:5, b:2, c:1, d:1.

  • heap: (1,c), (1,d), (2,b), (5,a)
  • merge c+d → 2. heap: (2,b), (2,cd), (5,a)
  • merge b+cd → 4. heap: (4,bcd), (5,a)
  • merge → 9. root.

Depths: a=1, b=2, c=3, d=3. WEPL = 5·1 + 2·2 + 1·3 + 1·3 = 15. Note the tie at weight 2: merging b with cd versus merging the two weight-2 nodes in the other order gives a different tree shape but the same WEPL. That is the tie-instability point.

Why the greedy step is optimal

Exchange: take any optimal tree T, and let a and b be siblings at maximum depth. Swap the two rarest symbols x and y into those positions. The change in WEPL is (f_x − f_a)(d_a − d_x) + (f_y − f_b)(d_b − d_y). The first factor in each term is ≤ 0 and the second is ≥ 0, so each product is ≤ 0. T was optimal, so the change is 0 and the swapped tree is also optimal. Substructure: replacing x and y with a composite z of weight f_x + f_y adds exactly f_x + f_y to WEPL no matter where z ends up, so minimizing the reduced problem minimizes the original. Induction on n closes it.

Failure modes

  • Skewed distributions. Huffman is optimal in WEPL but not in worst-case codeword length. A Fibonacci-like frequency distribution forces depth n−1. Hardware decoders with fixed-width bit registers cannot handle that. Detect by computing max depth after building; if it exceeds your cap, you need a length-limited variant.
  • Length caps. DEFLATE caps codewords at 15 bits; plain Huffman can exceed it. zlib's fix is to halve all frequencies (rounding up to 1) and rebuild until max depth fits: a heuristic, not optimal, but fast. Package-merge gives the optimal length-limited code at higher cost.
  • Two-pass requirement. The decoder needs the frequency table, so you transmit it. That is why DEFLATE has a dynamic-Huffman header. For small blocks the header can dominate the payload, and fixed-length or a pre-shared table wins there.
  • Non-deterministic ties. Two encoders with the same frequencies can emit different trees unless tie-breaking is pinned, which breaks byte-for-byte reproducibility across versions.

Trade-offs

  • Fixed-length codes: ⌈log₂ n⌉ bits per symbol, no table, O(1) decode. Huffman wins on skewed data; on near-uniform data the table overhead plus near-identical lengths make it a wash.
  • Canonical Huffman: same WEPL, but codewords are assigned in length order so the decoder only needs the length list, not the tree. This is what DEFLATE and most real formats use.
  • Arithmetic/range coding: within a fraction of a bit of entropy, versus Huffman's up to 1 bit/symbol gap from integer lengths. Chosen when the last few percent matter more than decode speed.
  • When Huffman is wrong: probabilities drift over the stream (use adaptive Huffman or context modeling), you need sub-bit precision (arithmetic), or the alphabet is so large the table dominates (fixed or hybrid code).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How do Kruskal's and Prim's algorithms utilize the greedy cut property to build a Minimum Spanning Tree, and how do their data structure choices affect time complexity?

Answer

Both algorithms build an MST by repeatedly applying the cut property: for any cut $(S, V \setminus S)$, a minimum-weight edge crossing it is safe. Some MST contains it.

Prim's makes the cut explicit. $S$ is the tree so far; it takes the lightest edge from $S$ to $V \setminus S$ and pulls that vertex into $S$. Kruskal's scans edges in non-decreasing weight and adds $(u,v)$ when $u$ and $v$ sit in different components. The cut is implicit: let $S$ be $u$'s component just before the add. Any edge $f$ crossing $(S, V\setminus S)$ with weight below $w(u,v)$ was scanned earlier; at that moment $u$'s component was a subset of $S$ and $f$'s far endpoint lay outside it, so Kruskal would have added $f$, merging its endpoints, but components never split, so at the later moment $f$'s endpoints would still be in one component, contradicting that $f$ crosses the cut. So $(u,v)$ is a lightest crossing edge.

AlgorithmCore structureTimeBest topology
Kruskaledge sort + DSU$O(E \log E)$sparse
Prim, binary heapmin-heap + decrease-key$O(E \log V)$sparse
Prim, adjacency matrixlinear scan of a key array$O(V^2)$dense, $E \approx V^2$
Prim, Fibonacci heapheap with $O(1)$ decrease-key$O(E + V \log V)$dense, theoretical

What breaks

  • Disconnected graph. No spanning tree exists. Kruskal returns a spanning forest and the loop ends with fewer than $V-1$ edges; Prim started in one component drains its heap with vertices unvisited. Detect by asserting len(mst) == V-1 or visited == V and reporting "disconnected" rather than returning a forest. Trace on $A..E$ with edges $(1,A,B), (2,B,C), (3,A,C), (4,C,D)$:

    edgecomponents beforeaction
    (1,A,B)A, Badd → {A,B}
    (2,B,C){A,B}, Cadd → {A,B,C}
    (3,A,C){A,B,C}, {A,B,C}reject, cycle
    (4,C,D){A,B,C}, Dadd → {A,B,C,D}

    $E$ is isolated, so len(mst) == 3 < 4. A Prim run from $A$ visits four vertices and stops.

  • Duplicate weights. Ties mean several distinct MSTs exist, so the cut property gives "a lightest crossing edge", not "the lightest". Both algorithms still return a valid MST; the failure is in testing: asserting equality against one expected edge set fails on correct code. Compare total weight, or verify the spanning-tree and cut conditions. Sorting (w, u, v) tuples breaks ties by u then v, so output is deterministic for a fixed input order.

  • DSU without union by rank. Path compression alone is $O(\log V)$ amortized per operation, union by rank alone is $O(\log V)$, both together $O(\alpha(V))$. Drop both, always parent[root_x] = root_y, and an adversarial edge order builds a chain of depth $V$: find costs $O(V)$ and Kruskal degrades to $O(EV)$. Detect by tracking the maximum depth reached during find.

  • Stale heap entries in lazy Prim. Lazy Prim pushes a fresh (weight, v) on every relaxation instead of calling decrease-key, so the heap holds up to $E$ entries and each pop must skip vertices already in the tree. Skip that check and a vertex enters the MST twice and the weight is overcounted. Detect by asserting len(mst) == V-1 and that every popped vertex was unvisited; memory is $O(E)$, not $O(V)$.

Choosing. Dense graph: array-based Prim, $O(V^2)$ with no heap overhead. Sparse: either. Kruskal if edges are already sorted or bucket-sortable to $O(E)$, Prim if the graph is an adjacency structure you can walk. Streaming edges from external storage: Kruskal, since Prim needs random vertex access.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does dijkstra as a greedy algorithm change if the workload grows by two orders of magnitude?

Answer

Core answer (first 90 seconds)

The greedy step does not change. Dijkstra finalises the nearest unfinalised vertex, and with non-negative weights that choice is provably safe at 10 nodes or 10 million: scale never touches the invariant. What changes at 100x is the cost profile: the priority queue, not the greedy decision, becomes the bottleneck, and the failure modes move from "wrong answer" to "out of memory" and "p99 latency".

Where the work goes

Binary-heap Dijkstra is O((V + E) log V). Each edge relaxation that improves a tentative distance pushes onto the heap (lazy deletion) or does a decrease-key; the greedy selection is one extract-min per finalised vertex, so V of them. Heap work therefore scales with E, each operation costing log V.

Illustrative road-like graph, average degree 4:

VEheap ops ≈ E·log Vdist array (8 B/entry)
baseline1M4M4M × 20 ≈ 80M8 MB
100x100M400M400M × 27 ≈ 10.8B800 MB

Wall time grows slightly faster than 100x because log V creeps from ~20 to ~27, but the dominant term is the 100x on E.

Memory is the sharper edge. With lazy deletion the heap can hold one entry per relaxation: up to O(E) stale entries. At 400M entries × 16 bytes that is roughly 6.4 GB of heap against 800 MB of distances. That, not the arithmetic, is what kills the run.

What you reach for instead

ApproachWhen it winsCost
Plain binary-heap Dijkstrasingle source, moderate graph, no heuristicO((V+E) log V)
Bidirectional Dijkstrapoint-to-point on road-like graphsexplores ~2× fewer nodes (two radius-r/2 searches vs one radius-r)
A* with admissible heuristicyou have coordinates or a lower boundexplored nodes depend on heuristic quality
Contraction hierarchies / hub labellingstatic graph, many queriesheavy preprocessing, microsecond queries
Bellman-Fordnegative edges presentO(VE), strictly worse otherwise

Deciding criterion: one query. Plain Dijkstra with a binary heap, and fix memory by sharding or streaming. Many point-to-point queries on a static graph: preprocess (CH or hub labelling); the 100x query load is exactly what makes preprocessing pay off. A good heuristic available: A* is a drop-in that cuts explored nodes with no preprocessing.

Failure modes at scale

  • Heap blowup from lazy deletion: track heap size against V; fix with decrease-key or periodic rebuild.
  • Cache misses: once heap and distance array exceed L3, each extract-min is a memory stall, not a CPU op. P99 rises far more than the mean.
  • Single-threaded ceiling: Dijkstra parallelises poorly; Δ-stepping helps on low-diameter graphs with small integer weights.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How does local optima and hill climbing interact with rollback, and where do people ignore that?

Answer

Core answer. Hill climbing accepts a move only when it improves the objective; rollback is the undo. They interact in one decisive way: rolling back to the best-so-far is the greedy rule. A system that reverts every worsening move can never cross a valley, so it terminates at the first local optimum no matter how much rollback machinery it has. Rollback only buys escape when the target is a checkpoint you keep exploring from (the last accepted state, or a fresh restart) not the incumbent best.

That is where people ignore it: they add rollback for safety (canary revert, config rollback, checkpoint restore) and then reuse it as the search policy. The search silently becomes greedy, and the rollback that was supposed to make exploration safe is the thing forbidding it.

Worked trace. Objective f over integer states 0..6: f = [0, 3, 5, 4, 8, 6, 2]. Start at x=2 (f=5). Global optimum is x=4 (f=8).

  • Rollback-to-best: x=2→3 gives 4 < 5, revert to 2. x=2→1 gives 3 < 5, revert. No improving neighbour, terminate at x=2, f=5. Local optimum.
  • Rollback-to-checkpoint: x=2→3 (f=4), keep it, checkpoint x=2 retained. x=3→4 (f=8 > 4), accept. Now at the global optimum. Roll back to x=2 only if the budget runs out.

Same rollback primitive, opposite outcome; the only difference is the target.

Failure modes and detection.

  • State restored, measurement not. You revert the config but not the plan cache, buffer pool, warmed JIT or table statistics, so the "same" state measures differently the second time. Detect with A/B/A: run config A, then B, then A again; if the two A measurements differ beyond noise, rollback is incomplete.
  • Zero accepted worsening moves. Log accepted moves; if none are non-improving, you have no escape mechanism whatever the code calls it.
  • Rollback cost prices out exploration. If checkpoint+restore exceeds evaluation time, the search takes few exploratory moves and drifts back to greedy. Measure both.
  • Non-reversible side effects. DDL, sent mail, payments, consumed queue messages, cache evictions. Reverting the decision variable doesn't undo these; any move with a non-idempotent side effect can't be in the search space.

Trade-offs.

PolicyRollback targetEscapes local optimumMain cost
Greedybest-so-farNo: this is greedynone
Simulated annealinglast acceptedYes, via temperaturecheap state restore
Random restartsfresh stateYes, probabilisticallycheap re-init
Tabu / lookaheadnone neededYes, via memorymemory of visited states

Pick annealing when state restore is cheap and the landscape is smooth; restarts when re-init is cheap and the landscape is rugged; tabu when state is expensive to snapshot but cheap to remember.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

When would you refuse a design because of sorting by a composite key?

Answer

I refuse when the composite key is a lexicographic concatenation of two attributes that the objective actually trades off continuously. The key then asserts an absolute priority the rule never agreed to, and it produces a specific wrong order.

Assume the objective is known and expressible as a number per item. If it is, the sort key should be that number, not a tuple.

Worked example: ranking results where the rule is "maximise relevance minus 0.5 × latency in seconds":

itemrelevancelatencyscore = rel − 0.5·lat
X0.90500 ms0.65
Y0.8910 ms0.885

The composite key (relevance desc, latency asc) returns X, Y. The objective returns Y, X. The lexicographic key is wrong by construction: it treats a 0.01 relevance gap as dominating a 490 ms latency gap, which is not the rule.

The tie case is where the two diverge further. For Smith's rule, minimise total weighted completion time on one machine, the key is the ratio p/w, and equal ratios are genuinely equivalent:

A: p=1, w=10 → ratio 0.1; B: p=10, w=1 → ratio 10. A then B gives 1·10 + 11·1 = 21. B then A gives 10·1 + 11·10 = 120.

Two jobs with equal ratio, A: p=2, w=4 and B: p=3, w=6, both 0.5: A,B gives 2·4 + 5·6 = 38; B,A gives 3·6 + 5·4 = 38. Ties in the ratio are free. Ties in a lexicographic key are not: they hide the trade-off you failed to encode.

Alternatives, and when each is right:

  • Scalarise with explicit weights, and take the weights from the objective, not from intuition. Right when the trade-off is continuous and you can defend the weights.
  • Keep the tuple only when the priority is genuinely absolute: "never rank a stale document above a fresh one" is a real lexicographic rule, and then the tuple is correct.
  • For genuine multi-objective ranking, return a Pareto frontier or top-k per objective and let the caller decide.

Failure modes and detection:

  • Intransitive comparator. A key like (score desc, recency asc) where score is a float rounded inconsistently can violate transitivity. Java's TimSort throws IllegalArgumentException: Comparison method violates its general contract!; Python's list.sort does not validate and returns an order that depends on the input permutation. Detect by asserting the comparator is a strict weak ordering in a test, and by checking the sort is invariant under shuffling the input.
  • Silent lexicographic substitution. The wrong order looks plausible, so it ships. Detect by comparing the top-k against the objective function on a labelled sample.

So the refusal condition: if the objective is a continuous trade-off and the proposed key is a tuple, refuse and ask for the weights. If the priority is absolute, the tuple is fine.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about greedy in scheduling systems?

Answer

Two machines, five jobs, processing times 3, 3, 2, 2, 2 in that arrival order. Run greedy list scheduling: assign each job to the machine with the least load. Greedy makespan is 7. The optimal makespan is 6. That is the smallest experiment I know that falsifies greedy for makespan minimization.

Greedy is online: it commits the first two 3s to separate machines because both start empty. When the three 2s arrive, it balances them across the two machines, ending with loads 7 and 5. The optimal schedule puts both 3s on one machine (load 6) and all three 2s on the other (load 6). The information gap is the whole story: greedy cannot see the three 2s coming.

Python
import itertools

def greedy(m, jobs):
    loads = [0] * m
    for job in jobs:
        i = min(range(m), key=lambda x: loads[x])
        loads[i] += job
    return max(loads)

def optimal(m, jobs):
    best = float('inf')
    for assign in itertools.product(range(m), repeat=len(jobs)):
        loads = [0] * m
        for job, machine in zip(jobs, assign):
            loads[machine] += job
        best = min(best, max(loads))
    return best

jobs = [3, 3, 2, 2, 2]
print(greedy(2, jobs))   # 7
print(optimal(2, jobs))  # 6

Trace of the greedy run:

  • start loads [0, 0]
  • job 3 → machine 0, loads [3, 0]
  • job 3 → machine 1, loads [3, 3]
  • job 2 → machine 0, loads [5, 3]
  • job 2 → machine 1, loads [5, 5]
  • job 2 → machine 0, loads [7, 5]

max = 7. The optimal assignment is machine 0: 3+3=6, machine 1: 2+2+2=6, max = 6.

Greedy list scheduling is (2 − 1/m)-competitive, so on m=2 it is 1.5-competitive. Here the ratio is 7/6 ≈ 1.167, inside the bound. The experiment does not violate the guarantee; it shows the guarantee is not optimality. If you need optimality, greedy is the wrong tool. When not to use greedy: when you have the full job set and makespan is the objective, use an exact solver for small n or a better heuristic. Note that LPT (longest processing time first) also gives 7 on this instance: sort descending 3,3,2,2,2, assign 3→M1(3), 3→M2(3), 2→M1(5), 2→M2(5), 2→M1(7). So the experiment also shows that sorting descending does not fix it. The optimal requires a non-greedy grouping.

In production, this manifests as a few long jobs arriving early and many short jobs arriving later. Greedy spreads the long jobs, then the short jobs pile onto the already-loaded machines. Detection: compare makespan to a lower bound (total work / m) and to an offline schedule on a sample of the queue. If the gap is consistently > 10%, greedy is leaving capacity on the table.

If on this exact instance greedy produced 6, I would need a larger instance. It does not. So this is the smallest experiment that changes my mind.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites the cost of a wrong greedy rule but cannot apply it?

Answer

The question I'd ask is concrete, not conceptual: "Name a greedy rule you've used, give me an input where it returns a valid but suboptimal answer, and tell me how you'd have caught it before it shipped." A candidate who can only recite "greedy fails silently" stalls on the first clause. Everything after that is a follow-up on whatever they produce.

The counterexample I'm listening for. Coin change, largest-coin-first, denominations {1, 3, 4}, target 6:

  • Greedy: take 4, 2 left; take 1, 1 left; take 1 → 4+1+1, three coins.
  • Optimal: 3+3, two coins.

The greedy output sums to 6, so every validity check passes; it is just one coin worse. Producing that instance, not describing the phenomenon, is the whole test.

Then the follow-ups, in order:

  1. "How would you have caught it?" The honest answer is a reference optimum on small inputs: DP over amounts 0..6 costs O(amount × |coins|) and gives the true minimum, so you diff greedy against it across a generated input space. You cannot do this at production scale, you don't have the optimum, and a candidate who claims to compare against it there has not thought it through.
  2. "When is greedy actually safe?" For coin change, largest-first is optimal exactly when the system is canonical; {1, 5, 10, 25} is, {1, 3, 4} is not. The general tool is an exchange argument: show any optimal solution can be transformed into the greedy one without getting worse. If you can't write that argument, you have a hope, not a guarantee.
  3. "What do you do in production, where you can't compute the optimum?" You bound the gap. Greedy set cover, repeatedly take the set covering the most uncovered elements, is within H(n) = 1 + 1/2 + ... + 1/n ≤ ln n + 1 of optimal. You can compute the LP relaxation's value as a lower bound on the optimum and alert when greedy's cost drifts past that ratio. That is a named, checkable bound, not "monitor quality."

What a weak answer looks like: it names the mechanism, then says "test on small instances and monitor in production" with no rule, no instance, and no bound. The question is built so that sentence can't survive: you have to apply the idea to something.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

What belongs in a runbook section on when greedy is an approximation, and what does not?

Answer

What belongs: the ratio, the specific greedy it applies to, the instance shape where the bound bites, the metric that detects a blowup, and the fallback with its cost. What does not: the proof, a ratio quoted without naming the problem, and any heuristic with no proven bound dressed up as an approximation.

Why the bound is ln n. Set cover: universe of n elements, repeatedly pick the set covering the most uncovered elements. Let OPT = k. After t sets, n_t elements remain uncovered. The k optimal sets cover all n_t of them, so the best single set covers at least n_t/k, and greedy picks at least that many:

n_{t+1} ≤ n_t · (1 − 1/k)

After k·ln n steps, n_t ≤ n·e^{−ln n} = 1, so greedy finishes within k·ln n sets. The tighter statement is H(n) = 1 + 1/2 + … + 1/n ≤ ln n + 1, from the same argument applied to the harmonic sequence of remaining counts. Feige (1998) shows (1−ε)ln n is unreachable in polynomial time unless NP ⊆ DTIME(n^{O(log log n)}), so the log factor is not an artefact of the analysis.

Where it bites. n = 8, U = {a1..a4, b1..b4}. OPT is two sets: A = {a1..a4}, B = {b1..b4}. Greedy, adversarial tie-breaking:

stepset chosensizeuncovered after
1{a1,a2,b1,b2}44
2{a3,b3}22
3{a4}11
4{b4}10

Greedy 4, OPT 2. Scale to n = 2^k and greedy takes k+1 sets against OPT's 2: ratio (log₂n + 1)/2. The blowup is real and invisible on small or clustered inputs.

What belongs in the runbook:

  • The call site and the problem it solves: "select_cover_sets(). Set cover, greedy, H(n)-approximate."
  • The ratio with its source: "H(n) ≤ ln n + 1, Vazirani §2.1". A citation the on-call can open.
  • The instance shape where the bound bites: large candidate pool, near-uniform coverage, no dominant set.
  • The detection metric: greedy count vs the LP relaxation optimum. LP optimum ≤ OPT ≤ greedy, so greedy/LP is a computable lower bound on the true ratio. Alert above 3.
  • The fallback and its cost: LP rounding or primal-dual when max element frequency f ≤ 3 (f-approximation, better than ln n), ILP for n ≤ 10⁴.

What does not belong:

  • The proof. It goes in the code comment or the design doc.
  • "Greedy is a 2-approximation": that is vertex cover, not set cover. The constant is problem-specific: 2 for vertex cover, 1−1/e for max coverage, ln n for set cover.
  • A heuristic with no proven ratio labelled as an approximation. If there is no bound, the runbook says "heuristic, no bound, measure it."
  • Tuning knobs that do not move the guarantee.

Failure modes and detection:

  • Silent ratio blowup: greedy returns 40 sets where LP says 6. Detected by the LP lower bound, not by wall-clock.
  • Tie-breaking sensitivity: two runs with shuffled set order return different counts. Detected by running twice; differing counts mean the instance sits near the boundary and the ratio is not stable.
  • Mislabelled heuristic: greedy for max coverage is 1−1/e only for the coverage objective. If the runbook claims it covers all elements within 1−1/e, the on-call trusts a bound that does not exist.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How would you review a pull request whose risk is greedy versus dynamic programming?

Answer

What I'd say first

The review isn't "greedy or DP": it's "does this PR carry evidence that the greedy choice is safe on the inputs we actually see?" A greedy swap is a correctness change wearing a performance change's clothes, so I review it as one: I want the exchange argument or a counterexample, and I want the test suite to contain the adversarial input. Without one of those, I don't approve.

The procedure

  1. Read the diff for what actually changed. A DP replaced by a greedy is a different algorithm; a greedy fast path added in front of a DP that still runs as fallback is a different risk. Ask which one this is.

  2. Ask for the exchange argument. For interval scheduling it's one line: earliest finish time leaves the most room for the rest. If the author can't state it, that's the review comment, not a style nit.

  3. If there's no proof, hunt a counterexample before reading anything else. Coin change is the standard trap.

Trace: denominations [1, 3, 4], amount 6.

  • Greedy: largest ≤ 6 is 4, remainder 2 → 1, remainder 1 → 1. Three coins.
  • Optimal: 3 + 3. Two coins.

Greedy returns 3, the optimum is 2. The PR is wrong on this input.

  1. Check the tests. This bug hides because US coins {1, 5, 10, 25} form a canonical system where greedy is provably optimal, so a suite built on those passes. The review asks for a non-canonical case like [1, 3, 4] and a large amount.

  2. Check the complexity claim, because that's the whole reason for the PR. Coin change DP is O(n·W) time, O(W) space with a rolling array. Greedy is O(n log n) to sort once, O(n) per query. With n = 4 and W = 10^9, the DP is 4×10^9 operations, infeasible, so the greedy is tempting exactly where it's most likely to be wrong.

  3. Decide. Block if the greedy-choice property is unproven and inputs are adversarial. Approve with a comment if the domain guarantees it: a matroid, a canonical coin system, or earliest-finish interval scheduling.

Where greedy is provably safe

ProblemGreedyDP
Fractional knapsackoptimal (value/weight ratio)unnecessary
0/1 knapsackwrongO(nW)
Interval schedulingoptimal (earliest finish)unnecessary
Coin change, canonicaloptimalunnecessary
Coin change, arbitrarywrongO(nW)

Failure modes and how I detect them

The failure is a fast wrong answer that passes CI. Detection: the counterexample above, plus a property test comparing greedy against a brute-force DP on random small inputs. If the author adds that test and it passes, the review is nearly done. If they argue from "it worked on our data", I ask for the input distribution: the ordering or scale that breaks it is exactly what a quick check omits.

The senior move is to make the assumption visible in the code: a comment naming the greedy-choice property and the input class it holds for, so the next person knows what would invalidate it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you brief product on why stability of the greedy order delays a ship date?

Answer

What I'd say in the first 90 seconds

The ship date moves because a number we already showed product can change between two runs over identical input. Our allocator fills fixed-size slots greedily by value per unit of weight. When two candidates have the same ratio, the one that gets the slot is whichever one the list handed the sort first, and we never wrote down what should happen on a tie. So the output is reproducible only by accident of input order. Pinning a tie-break is about four hours of code. Proving the change doesn't move a customer-facing number is the rest of the week, and that is the work that eats the date.

The 10-minute version for the room

Worked example, hypothetical numbers, real arithmetic. Slot budget of 10 units, three candidates whose value-per-weight ratio is identical at 1.0: A weighs 6 and carries 6, B weighs 5 and carries 5, C weighs 4 and carries 4.

orderwhat the greedy takesvalue packed
A, B, CA fits, B would make 11, C fits10
C, B, AC fits, B fits at 9, A would make 159
B, A, CB fits, A would make 11, C fits at 99

Three candidates, one budget, 10 units of value in one order and 9 in another. Nothing in that code is a bug; there is simply no rule for the tie. The real system has many more candidates sitting on the cut line, so the spread is wider. Measure it rather than trusting my numbers: shuffle one day's candidate list 100 times, rerun, and look at the spread in total value. That spread is the exposure, and it is the figure product should see.

Why the input order isn't ours to control

Two things get called stability here. Sort stability is the documented promise that equal keys keep their input order. Stability of the greedy result is what that promise buys us: an answer that doesn't depend on which order the candidate list arrived in. We only get the second if we have the first and the input order is fixed.

In practice it isn't. Hash map iteration order is unspecified. A parallel reduction over an unordered stream combines values in whatever order the threads finish. And the sort guarantee depends on the call shape: in Java, Arrays.sort over primitives is dual-pivot quicksort and unstable, while Arrays.sort over Object[] is TimSort and stable. Python's sorted is documented as stable. Same-looking call, different guarantee, and a library upgrade can hand you the other one.

The two questions that decide the date

  1. Does the tie change the value, or only its form? Two candidates with the same ratio and the same slot revenue make the tie cosmetic: add an explicit tie-break on id, ship on time, note it in the changelog. If the tie changes revenue, fill rate, or which advertiser wins the slot, it is a correctness change and has to be re-validated.
  2. Is the number externally reported? If a client sees it, or we contract on it, every rerun is a change of record and needs a diff and a sign-off.

Where the week goes (estimate, not a measurement)

  • 4 hours: implement the tie-break the policy dictates.
  • 1 day: determinism test (same input, 100 shuffles, total must be identical) wired into CI.
  • 2-3 days: replay 90 days of stored input through the pinned rule and diff against frozen output, counting how many days move and by how much.
  • 1 day: analyst sign-off on the diffs, plus a note on any customer-facing number that changed.
  • 1 day of buffer for the ad-ops conversation if a slot changes hands.

What I need from product

One decision: on a tie, who wins the slot? Highest margin, oldest campaign, lowest id: any of those is defensible. If they answer today, we ship on the current date. If they can't, default to lowest id, which is arbitrary but deterministic, and treat any later change to that policy as a new change with its own validation.

How we stop paying for this again

The determinism test in CI is the whole defence. Run the pipeline twice with the input shuffled; if the summary metric differs, the build fails. It costs one test and catches every future tie, not just this one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you document recognising a greedy problem so the next owner can operate it?

Answer

What the artefact is

The handover is a greedy decision record: a short file checked in next to the solver, not a wiki page. Four fields, because those are the four things the next owner needs to change the code safely: the ordering, the exchange argument in three lines, the invariant it preserves, and the counterexample input that kills the ordering a reader would try first. Plus the test that pins it.

# greedy: interval scheduling (max non-overlapping)
ordering:       sort by finish time ascending
invariant:      after k picks, the k-th finish is the earliest achievable
                for any k-interval solution
exchange arg:   any optimal solution can swap its first interval for the
                earliest-finishing one without losing a later pick
counterexample: [[0,10],[1,2],[3,4]]  -> earliest-start gives 1, this gives 2
test:           test_interval_scheduling.py::test_earliest_start_counterexample
wrong-when:     intervals carry weights -> DP over sorted finishes, O(n log n)

That last line is the one people omit and the one that saves the next owner. It states the boundary of the guarantee, so nobody extends the solver into a regime where the exchange argument no longer holds.

The counterexample, traced

Run both orderings on [[0,10],[1,2],[3,4]].

  • Earliest start: sorted by start: [0,10],[1,2],[3,4]. Take [0,10], last finish 10. [1,2] starts at 1 < 10, skip. [3,4] starts at 3 < 10, skip. Count 1.
  • Earliest finish: sorted by finish: [1,2],[3,4],[0,10]. Take [1,2], finish 2. [3,4] starts at 3 ≥ 2, take, finish 4. [0,10] starts at 0 < 4, skip. Count 2.

The record carries this input verbatim so the next owner can re-derive the ordering rather than trust it.

Alternatives and when to pick them

Greedy is one of three, and the record should say which the code is and why the others were rejected.

ApproachUse whenCost
Greedythe exchange argument holds: a local choice never hurts a later oneO(n log n) for the sort
DPthe objective is additive under a capacity constraint, so a local choice canO(n·W) or O(n²)
Brute forcen is small: keep it as a test oracle, not as the shipped pathexponential

The deciding question is whether the choice has the exchange property. Fractional knapsack does; 0/1 knapsack does not. Capacity 50, items (60,10),(100,20),(120,30): density-greedy takes 10+20 and scores 160, while DP takes 20+30 and scores 220. Same items, same ordering, different problem, which is exactly why the record names the regime.

Failure modes and how they are detected

  • Ordering chosen by intuition, not by the exchange argument. Detect with a differential test: run the greedy against brute force on random inputs with n ≤ 12 and assert equal answers.
  • Correct unweighted, silently wrong once weights are added. Detect with a property test asserting greedy == DP on random weighted inputs; the 160-vs-220 case above is the seed.
  • Tie-breaking unspecified (equal finish times, equal densities). Detect by shuffling equal-key inputs and asserting the answer is unchanged.

Each of these is a test in the repo, not a paragraph in the record. The record points at them; the tests are what actually stop the next owner.

Curated: · Written: · Reviewed:

Difficulty: Medium