Knowledge / Computer Science and Engineering / Greedy algorithms

Greedy algorithms

Computer Science and Engineering (B.E./B.Tech) · Algorithms · free study notes for exams, placements and interviews

In short

A greedy algorithm builds a solution one step at a time, each time taking the choice that looks best right now and never undoing it. It is correct only when the problem has the greedy-choice property (a locally best first move is contained in some globally optimal solution) and optimal substructure; otherwise it gives a fast but wrong, or merely approximate, answer. The greedy method is a named unit in every AICTE/CBCS "Design and Analysis of Algorithms" course and appears in GATE CS almost every year through knapsack, Huffman codes, job sequencing and spanning-tree questions. In interviews at Amazon India, Flipkart, Walmart Global Tech, Zomato, Swiggy, Ola, Uber, Microsoft IDC, Google India and the service majors (TCS Digital, Infosys HackWithInfy, Wipro, Accenture), greedy interval and scheduling questions are standard, and the interviewer's real question is usually "prove your greedy is correct, or show me where it breaks".

Explained

What makes a problem solvable greedily

Designing and proving a greedy algorithm

  1. Cast the problem as making a sequence of choices; list the plausible greedy criteria (smallest, largest, earliest finish, best value-per-weight, earliest deadline).
  2. Sort or heapify by that criterion; prove the first choice is safe; prove the remainder is the same problem on fewer items; then write the loop.
  3. Exchange argument (most used in exams): take any optimal solution O; if its first choice differs from the greedy choice g, swap g in for that element; show the result is still feasible and no worse. Repeating converts O into the greedy solution, so greedy is optimal. Used for activity selection, job sequencing and Kruskal.
  4. "Greedy stays ahead" (induction): show that after each step the greedy partial solution is at least as good as any other partial solution on a chosen measure (e.g. after k activities, greedy's finish time is the earliest possible).
  5. Matroid theory (the general theorem): if the feasible sets form a matroid — non-empty, hereditary (subsets of an independent set are independent) and satisfying the exchange property (|A| < |B| ⇒ some x ∈ B∖A keeps A ∪ {x} independent) — then the greedy algorithm on weights gives a maximum-weight independent set. Kruskal's algorithm is exactly greedy on the graphic matroid; job sequencing with deadlines is greedy on a transversal matroid.
  6. Disproving a greedy: one small counter-example is a complete proof of incorrectness. Always test tiny inputs (n = 2, 3) and equal-key ties.

The classic greedy problems on the syllabus

Greedy inside graph algorithms (brief — detailed in their own notes)

Greedy results in scheduling (single machine, as examined)

When greedy can only approximate, and its limits

Key points

Formulas and examples

Greedy correctness = greedy-choice property + optimal substructure. Both must hold; one alone is not enough.
Activity selection: pick activity i, then recurse on { j : s_j ≥ f_i }, scanning in non-decreasing f order. s = start time, f = finish time.
Fractional knapsack: maximise Σ v_i x_i subject to Σ w_i x_i ≤ W, 0 ≤ x_i ≤ 1. Greedy order: v_1/w_1 ≥ v_2/w_2 ≥ … (v = value in ₹, w = weight in kg, W = capacity in kg).
Huffman / optimal merge cost: B(T) = Σ f_i · d_i = Σ (values of all internal nodes). f_i = frequency or file length, d_i = depth = code length in bits.
Average code length L = B(T) / Σ f_i bits per symbol; space saving = (fixed-length bits − Huffman bits) / fixed-length bits.
Minimum platforms = max over time t of | { trains with arrival ≤ t ≤ departure } | (maximum interval overlap).
Mean retrieval time (tapes, SPT order l_1 ≤ l_2 ≤ … ≤ l_n): MRT = (1/n) Σ_{j=1..n} Σ_{i=1..j} l_i
Total completion time under SPT: Σ C_j = Σ_{j} (n − j + 1) p_j, with p_1 ≤ p_2 ≤ … (p = processing time).
Greedy set cover: cost_greedy ≤ H(n) × OPT, where H(n) = 1 + 1/2 + … + 1/n ≈ ln n + 0.577.

Example 1 — Activity selection (11 activities). (s, f) = (1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12), (2,14), (12,16).

def max_activities(acts):              # acts = [(start, finish), ...]
    acts.sort(key=lambda a: a[1])      # earliest finishing first
    chosen, last_end = [], float('-inf')
    for s, f in acts:
        if s >= last_end:              # compatible with the last pick
            chosen.append((s, f)); last_end = f
    return chosen                      # O(n log n) time, O(1) extra space

Example 2 — Fractional vs 0/1 knapsack. Capacity W = 50 kg. Items: A (₹60, 10 kg), B (₹100, 20 kg), C (₹120, 30 kg).

Fractional knapsack0/1 knapsack
Items divisibleYesNo
MethodGreedy on v/wDP (or branch and bound)
ComplexityO(n log n)O(nW) time, O(W) space
Example answer (W = 50)₹240₹220
Greedy by ratioOptimalNot optimal; ½-approximation only when paired with the best-single-item check
def frac_knapsack(items, W):           # items = [(value, weight)]
    items.sort(key=lambda i: i[0] / i[1], reverse=True)
    total = 0.0
    for v, w in items:
        if W >= w: total += v; W -= w
        else:      total += v * W / w; break
    return total                       # 240.0 for the data above

Example 3 — Huffman code for 100 characters. Frequencies: a 45, b 13, c 12, d 16, e 9, f 5.

import heapq
def huffman_cost(freqs):
    h = list(freqs); heapq.heapify(h); cost = 0
    while len(h) > 1:
        a = heapq.heappop(h); b = heapq.heappop(h)
        cost += a + b                  # value of the new internal node
        heapq.heappush(h, a + b)
    return cost                        # huffman_cost([45,13,12,16,9,5]) -> 224

Example 4 — Job sequencing with deadlines. J1 (₹100, d = 2), J2 (₹19, d = 1), J3 (₹27, d = 2), J4 (₹25, d = 1), J5 (₹15, d = 3). Unit-time jobs, slots 1–3 (max deadline).

Example 5 — Optimal merge / minimum platforms.

Where it is used

Interview questions

Common mistakes

Related topics

Dynamic programming · Minimum spanning trees and network flow · Graph algorithms: BFS, DFS and shortest paths · Sorting algorithms · Time and space complexity · DSA interview patterns

Open in the Knowledge reader →Find jobs →