Skip to main content

Algorithms

Greedy Algorithms

Greedy questions test whether you can recognise the correct greedy criterion, run it by hand (activity selection, Huffman, MST, job sequencing), and know exactly when greedy gives a wrong answer.

~4 hrs ~1–1.5 marks · High 10 samples · 10 practice · 10 cards

GATE CSE greedy algorithms — greedy-choice property, exchange argument, activity selection, fractional vs 0/1 knapsack, Huffman coding, Kruskal and Prim as greedy MST algorithms, and when greedy fails.

Learning outcomes

  • State the greedy-choice property and optimal substructure and explain the exchange argument
  • Run activity selection, fractional knapsack, Huffman coding and job sequencing by hand
  • Compute Huffman code lengths, total encoded size and tree node counts
  • Identify problems where greedy fails (0/1 knapsack, arbitrary coin systems) with counterexamples

Greedy paradigm and correctness

  • A greedy algorithm builds a solution step by step, always taking the locally best choice by some fixed criterion and never reconsidering it.
  • It is correct only if the problem has the GREEDY-CHOICE PROPERTY (some globally optimal solution contains the greedy first choice) and OPTIMAL SUBSTRUCTURE (the rest of the problem after the choice is a smaller instance of the same problem).
  • Exchange argument: take any optimal solution; if it does not contain the greedy choice, swap one of its elements for the greedy choice without making it worse. Hence a greedy-containing optimum exists.
  • Greedy usually has simple running time dominated by sorting or a priority queue: Θ(n log n).
  • Greedy works for: activity selection, fractional knapsack, Huffman coding, MST (Kruskal, Prim), Dijkstra (non-negative weights), job sequencing with deadlines. It FAILS for 0/1 knapsack, general coin change, longest path, and TSP.
  • Proof template: (1) show some optimal solution contains the greedy choice (exchange argument), (2) show what remains is a smaller instance of the same problem (optimal substructure), (3) conclude by induction. Matroid structure explains why MST and job sequencing are greedy-solvable.
  • "Greedy stays ahead" is the second standard proof style: show that after every step the greedy partial solution is at least as good as the corresponding partial solution of any other algorithm (used for activity selection and Dijkstra).
  • A criterion that is optimal for one objective may fail for another: earliest finish maximises the NUMBER of activities, but maximising total weight of chosen activities (weighted interval scheduling) needs dynamic programming.
  • Other classic greedy results: minimising maximum lateness uses earliest-deadline-first; minimising total waiting time uses shortest-job-first; optimal merge pattern for files is Huffman-like (merge the two smallest).
ProblemGreedy criterionOptimal?Time
Activity selectionEarliest finish timeYesΘ(n log n)
Fractional knapsackHighest value/weight ratioYesΘ(n log n)
0/1 knapsackHighest value/weight ratioNo (use DP)—
Huffman codingMerge two least frequentYesΘ(n log n)
Job sequencing (unit time)Highest profit firstYesΘ(n²) or Θ(n log n)
Coin change {1, 3, 4}Largest coin firstNo—

Worked example

Problem. Coins {1, 3, 4}, make 6. Compare greedy (largest coin first) with the optimum.

Solution. Greedy: 4 + 1 + 1 = 3 coins. Optimal: 3 + 3 = 2 coins. Greedy fails for this coin system.

Activity selection and job sequencing

  • Activity selection: given n activities with start/finish times, choose the maximum number of mutually compatible (non-overlapping) activities. Sort by FINISH time, take the first, then repeatedly take the next activity whose start ≥ last chosen finish. Time Θ(n log n) for the sort.
  • Other greedy criteria (earliest start, shortest duration, fewest conflicts) are NOT always optimal; only earliest finish is guaranteed.
  • Proof idea (exchange): replace the first activity of any optimal solution by the activity with the earliest finish; compatibility is preserved.
  • Job sequencing with deadlines (unit time jobs): sort jobs by profit descending; place each job in the latest free slot at or before its deadline; skip it if none is free. Maximises total profit.
  • Interval partitioning (minimum rooms/machines) equals the maximum depth (maximum number of overlapping intervals) and is solved greedily by sorting by start time.
  • Why earliest finish works (stays ahead): the k-th activity chosen by greedy finishes no later than the k-th activity of any other feasible schedule, so greedy always leaves at least as much free time for what follows.
  • If the activities are already sorted by finish time the scan is Θ(n); otherwise the sort dominates and the total is Θ(n log n).
  • Counterexamples for wrong criteria: shortest duration fails on (0,5), (4,6), (5,10) — it picks (4,6) and gets 1, while (0,5), (5,10) gives 2. Earliest start fails on (0,100), (1,2), (3,4) — it picks (0,100) and gets 1, while the other two give 2.
  • Interval partitioning example: (1,4), (2,5), (3,6), (5,8). At time 3.5 three intervals overlap, so the minimum number of rooms is 3 (the interval (5,8) can reuse the room of (1,4) or (2,5)).
  • Job sequencing implementation: the simple slot scan is Θ(n²); using a disjoint-set (Union-Find) structure to find the latest free slot makes it near Θ(n log n) after sorting.
JobDeadlineProfit
J12100
J2119
J3227
J4125
J5315

Worked example

Problem. Activities (start, finish): (1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12), (2,14), (12,16). Maximum compatible set size?

Solution. Earliest finish order picks (1,4), then (5,7), then (8,11), then (12,16): 4 activities.

Timeline of eleven activities sorted by finish time with the greedy choices (1,4), (5,7), (8,11) and (12,16) highlighted
Activity selection by earliest finish time picks four compatible activities.

Knapsack: fractional versus 0/1

  • Fractional knapsack: items can be split. Sort by value/weight ratio descending and take whole items until the next one does not fit, then take a fraction of it. Greedy is optimal; time Θ(n log n).
  • 0/1 knapsack: each item is taken whole or not at all. Greedy by ratio can be arbitrarily bad; the problem needs dynamic programming in Θ(nW) time (pseudo-polynomial) and is NP-complete.
  • The fractional optimum is always ≥ the 0/1 optimum for the same instance, because the 0/1 solutions are a subset of the fractional ones.
  • Why greedy works for fractional: any leftover capacity is filled with the best remaining ratio, so no exchange can improve the value.
  • Fractional knapsack is a linear program: maximise Σ v_i x_i subject to Σ w_i x_i ≤ W and 0 ≤ x_i ≤ 1. The greedy optimum has AT MOST ONE fractional item.
  • The fractional optimum is an upper bound for the 0/1 optimum; branch-and-bound algorithms for 0/1 knapsack use it for pruning.
  • Ratio-greedy can be arbitrarily bad for 0/1: with capacity W and items (value, weight) = (2, 1) and (W, W), greedy takes (2, 1) first (ratio 2), after which (W, W) does not fit; value 2 against an optimum of W.
  • Sorting by ratio costs Θ(n log n); if the items are already sorted by ratio the fractional greedy itself is Θ(n).

Formulas to remember

  • ratio_i = v_i / w_i
  • Fractional value = Σ (whole items) + (remaining capacity) × (ratio of the split item)

Worked example

Problem. Capacity 50; items (value, weight) = (60, 10), (100, 20), (120, 30). Find the fractional and 0/1 optimum.

Solution. Ratios 6, 5, 4. Fractional: items 1 and 2 (weight 30, value 160) plus 20/30 of item 3 (value 80) = 240. 0/1: best is items 2 and 3 = 220 (greedy by ratio would give only 160).

Knapsack of capacity 50 filled with item 1, item 2 and two thirds of item 3 in order of value to weight ratio
Fractional knapsack: take items by decreasing value/weight ratio; the last item may be split.

Huffman coding

  • Huffman coding builds an optimal PREFIX-FREE variable-length code: frequent symbols get short codes. A prefix code means no codeword is a prefix of another, so decoding is unambiguous.
  • Algorithm: put all symbols in a min-heap by frequency; repeatedly extract the two smallest, create a parent with their sum, and insert it back until one tree remains. Time Θ(n log n).
  • The tree is a FULL binary tree: every internal node has two children. With n symbols there are n leaves, n − 1 internal nodes and 2n − 1 nodes in total.
  • Total encoded size = Σ frequency × code length = sum of all internal-node weights created by merging.
  • Fixed-length coding uses ⌈log₂ n⌉ bits per symbol; Huffman never uses more bits on average. For equal frequencies and n = 2^k symbols Huffman equals fixed-length coding.
  • Ties between equal frequencies can give different codes but always the same optimal total cost.
  • Why the internal-node sum works: every symbol frequency is added once for each ancestor, i.e. depth times, so Σ f_i·d_i equals the sum of all internal-node weights.
  • Skewed (Fibonacci-like) frequencies give the most unbalanced tree: the longest code has n − 1 bits for n symbols and the shortest has 1 bit.
  • Decoding: read bits from the root, go left on 0 and right on 1, output a symbol on reaching a leaf and restart at the root. Symbols always sit at LEAVES; that is what makes the code prefix-free.
  • Implementation: with a binary min-heap there are n − 1 merges, each costing two extract-min and one insert, so O(n log n); if the symbols are pre-sorted a two-queue method runs in Θ(n).
  • In the example the two rarest symbols A:5 and B:9 become sibling leaves at the deepest level with codes 1100 and 1101; the most frequent symbol F:45 gets the 1-bit code 0.

Formulas to remember

  • Total bits = Σ f_i · d_i = Σ (weights of internal nodes)
  • Nodes = 2n − 1, internal nodes = n − 1

Worked example

Problem. Frequencies a:5, b:9, c:12, d:13, e:16, f:45. Find the total Huffman-coded size.

Solution. Merges: 5+9 = 14, 12+13 = 25, 14+16 = 30, 25+30 = 55, 45+55 = 100. Total = 14 + 25 + 30 + 55 + 100 = 224 bits (against 300 for fixed 3-bit codes).

Huffman tree for frequencies A 5, B 9, C 12, D 13, E 16 and F 45 with edge labels 0 and 1 and the resulting codes
Huffman tree for the classic frequencies; total cost 14 + 25 + 30 + 55 + 100 = 224 bits.

MST and shortest paths as greedy algorithms

  • A minimum spanning tree (MST) of a connected weighted undirected graph with V vertices has exactly V − 1 edges and minimum total weight.
  • Cut property: for any cut of the graph, the lightest edge crossing the cut belongs to some MST. Cycle property: the heaviest edge on any cycle is not in some MST (if it is the unique heaviest, it is in no MST).
  • Kruskal: sort edges by weight, add an edge if it does not form a cycle (use Union-Find). Time Θ(E log E) = Θ(E log V).
  • Prim: grow a single tree from a start vertex, always adding the lightest edge leaving the tree. Θ(V²) with adjacency matrix and array; Θ(E log V) with a binary heap and adjacency list.
  • If all edge weights are distinct, the MST is UNIQUE. Different MSTs of the same graph always have the same total weight.
  • Dijkstra is also greedy: it repeatedly settles the unsettled vertex with the smallest tentative distance (valid only for non-negative edge weights). See the Graph Algorithms topic for details.

Worked example

Problem. Graph on A, B, C, D with edges AB = 1, BC = 2, CD = 3, AD = 4, AC = 5. Find the MST weight.

Solution. Kruskal: take AB (1), BC (2), CD (3); AD (4) and AC (5) would form cycles. MST weight = 1 + 2 + 3 = 6.

Worked trace — Huffman with skewed frequencies

  • Frequencies 1, 1, 2, 3, 5, 8. Heap = {1, 1, 2, 3, 5, 8}. Merge the two smallest: 1 + 1 = 2. Heap = {2, 2, 3, 5, 8}.
  • Merge 2 + 2 = 4. Heap = {3, 4, 5, 8}. Merge 3 + 4 = 7. Heap = {5, 7, 8}. Merge 5 + 7 = 12. Heap = {8, 12}. Merge 8 + 12 = 20 (root).
  • Internal nodes created: 2, 4, 7, 12, 20 — that is n − 1 = 5 merges for n = 6 symbols, and 2n − 1 = 11 nodes in total.
  • Cost = 2 + 4 + 7 + 12 + 20 = 45. Check with depths: 8 has depth 1, 5 depth 2, 3 depth 3, 2 depth 4, and the two 1s depth 5: 8 + 10 + 9 + 8 + 5 + 5 = 45.
  • A fixed-length code would need ⌈log₂ 6⌉ = 3 bits for each of the 20 symbol occurrences = 60 bits, so Huffman saves 15 bits here.
  • When several heap entries tie (the two 2s above), either choice gives the same total cost 45, though the individual codewords may differ.

Worked example

Problem. Compute the Huffman cost for frequencies 3, 3, 3, 3 and compare it with fixed-length coding.

Solution. Merge 3 + 3 = 6 and 3 + 3 = 6, then 6 + 6 = 12. Cost = 6 + 6 + 12 = 24 bits = 12 × 2, the same as fixed 2-bit codes: equal frequencies with n = 2^k give no saving.

GATE exam tricks — when greedy works

  • Activity selection: sort by FINISH time. If an option says "earliest start" or "shortest duration" for maximising the count, it is wrong.
  • Fractional knapsack = greedy by ratio; 0/1 knapsack = DP. If a question says "items cannot be broken", greedy by ratio is a trap.
  • Huffman cost = sum of the weights of all internal nodes formed during merging. This avoids computing code lengths individually.
  • Huffman with n leaves has n − 1 merges and 2n − 1 nodes; for 8 symbols that is 7 merges and 15 nodes.
  • Counterexample drill: coin change {1, 3, 4} for 6, or ratio-greedy 0/1 knapsack items (60,10), (100,20), (120,30) with capacity 50.
  • MST questions: edges examined by Kruskal ≤ E; MST has V − 1 edges; unique if weights are distinct; Prim and Kruskal may produce different (equal-weight) trees when ties exist.
  • Exchange argument keywords in a statement ("swap an element of the optimal solution") point to the greedy-choice property proof.
  • Worked example 2 (job sequencing slots): jobs (deadline, profit) = (2, 60), (1, 100), (2, 20), (1, 40). Sort by profit: 100, 60, 40, 20. Job (1,100) takes slot 1; (2,60) takes slot 2; (1,40) and (2,20) find no free slot. Profit = 160.
  • Worked example 3 (greedy vs optimum): coins {1, 5, 10, 20, 25}, amount 40. Greedy gives 25 + 10 + 5 = 3 coins, but 20 + 20 = 2 coins is optimal, so greedy fails even for this realistic-looking system.
  • Elimination rule: if an option claims greedy is optimal for 0/1 knapsack, general coin change, TSP or longest path, reject it; if it claims greedy fails for fractional knapsack, activity selection by finish time or Huffman, also reject it.

Worked example

Problem. Job sequencing: use the table above (profit order J1 100, J3 27, J4 25, J2 19, J5 15). Find the maximum profit.

Solution. J1 → slot 2, J3 → slot 1, J4 (deadline 1) and J2 (deadline 1) have no free slot, J5 → slot 3. Profit = 100 + 27 + 15 = 142.

Exam tips

  • Always name the greedy criterion before simulating: finish time, ratio, smallest frequency, lightest edge, highest profit.
  • Use the internal-node-sum shortcut for Huffman total cost.
  • Check whether items are divisible; that single word decides greedy versus DP for knapsack.
  • Find a counterexample quickly with tiny instances when asked "does greedy always work?".
  • MST facts: V − 1 edges, unique when weights are distinct, Kruskal Θ(E log E), Prim Θ(V²) matrix or Θ(E log V) heap.
Exam pattern · 10 questions

GATE sample questions & answers

10 GATE-style MCQs for Greedy Algorithms with full explanations. Attempt each question before revealing the answer.

Q1 Activity selection

To select the maximum number of mutually compatible activities, a greedy algorithm should repeatedly choose the activity with:

  • A) Earliest start time
  • B) Shortest duration
  • C) Earliest finish time
  • D) Fewest conflicts
Show answer & explanation

Answer: C

Only the earliest-finish-time rule is provably optimal; the others have counterexamples.

Q2

A knapsack has capacity 50. Items (value, weight): (60, 10), (100, 20), (120, 30). Items may be taken fractionally. The maximum value is:

  • A) 160
  • B) 220
  • C) 240
  • D) 280
Show answer & explanation

Answer: C

Ratios are 6, 5, 4. Take items 1 and 2 (weight 30, value 160) and 20/30 of item 3 (value 80): total 240.

Q3 0/1 knapsack vs greedy

For the same items as above, but now each item must be taken whole (0/1 knapsack), the optimal value is:

  • A) 160
  • B) 180
  • C) 220
  • D) 240
Show answer & explanation

Answer: C

Feasible sets: items 1+2 = 160 (weight 30), 1+3 = 180 (weight 40), 2+3 = 220 (weight 50). The optimum is 220, while greedy by ratio picks 1+2 and gets only 160.

Q4

Symbols a, b, c, d, e, f have frequencies 5, 9, 12, 13, 16, 45. The total number of bits of the Huffman-coded message is:

  • A) 100
  • B) 224
  • C) 250
  • D) 300
Show answer & explanation

Answer: B

Internal node weights: 14, 25, 30, 55, 100. Their sum is 224 = Σ frequency × code length.

Q5

A Huffman tree is built for 8 distinct symbols. The total number of nodes in the tree is:

  • A) 8
  • B) 15
  • C) 16
  • D) 17
Show answer & explanation

Answer: B

A full binary tree with n leaves has n − 1 internal nodes, so 2n − 1 = 15 nodes.

Q6

Kruskal algorithm on a connected graph with V vertices and E edges, with sorting dominating, runs in:

  • A) O(V)
  • B) O(E log E)
  • C) O(V²)
  • D) O(E²)
Show answer & explanation

Answer: B

Sorting the edges costs Θ(E log E) (= Θ(E log V) since E ≤ V²), and Union-Find operations are almost linear.

Q7

Which of the following problems cannot be solved optimally by the usual greedy (ratio) strategy?

  • A) Fractional knapsack
  • B) 0/1 knapsack
  • C) Activity selection
  • D) Huffman coding
Show answer & explanation

Answer: B

Greedy by ratio can miss the optimal subset for 0/1 knapsack; it requires DP (or branch and bound).

Q8

For coin denominations {1, 3, 4} and amount 6, the greedy (largest-coin-first) algorithm and the optimal algorithm use (greedy, optimal) coins respectively:

  • A) (2, 2)
  • B) (3, 2)
  • C) (3, 3)
  • D) (2, 3)
Show answer & explanation

Answer: B

Greedy: 4 + 1 + 1 = 3 coins. Optimal: 3 + 3 = 2 coins.

Q9

If all edge weights of a connected undirected graph are distinct, then:

  • A) the MST is unique
  • B) the graph has exactly one spanning tree
  • C) Kruskal and Prim may give MSTs of different weights
  • D) the MST has V edges
Show answer & explanation

Answer: A

Distinct weights make the lightest edge across every cut unique, so the MST is unique. An MST always has V − 1 edges, and all MSTs have equal weight.

Q10

A graph has vertices A, B, C, D and edges AB = 1, BC = 2, CD = 3, AD = 4, AC = 5. The weight of its minimum spanning tree is:

  • A) 5
  • B) 6
  • C) 7
  • D) 10
Show answer & explanation

Answer: B

Kruskal accepts AB (1), BC (2) and CD (3); the remaining edges would close cycles. Weight = 6.

Topic drill · 10 questions

10 practice questions — Greedy Algorithms

Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.

P1

Activities (start, finish): (1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12), (2,14), (12,16). The maximum number of compatible activities is:

  • A) 3
  • B) 4
  • C) 5
  • D) 6
Show answer & explanation

Answer: B) 4

Greedy by finish time selects (1,4), (5,7), (8,11), (12,16).

P2

Prim algorithm with an adjacency matrix and linear-scan minimum selection runs in:

  • A) Θ(V)
  • B) Θ(V²)
  • C) Θ(E log V)
  • D) Θ(V³)
Show answer & explanation

Answer: B) Θ(V²)

V iterations, each scanning O(V) keys and updating neighbours via the matrix row.

P3

Prim algorithm with a binary heap and adjacency lists runs in:

  • A) O(V²)
  • B) O(E log V)
  • C) O(V log E)
  • D) O(E²)
Show answer & explanation

Answer: B) O(E log V)

Each edge may cause a decrease-key costing O(log V), and each vertex extraction costs O(log V): O((V + E) log V) = O(E log V) for connected graphs.

P4

The time complexity of the greedy fractional knapsack algorithm on n items is:

  • A) Θ(n)
  • B) Θ(n log n)
  • C) Θ(n²)
  • D) Θ(nW)
Show answer & explanation

Answer: B) Θ(n log n)

Sorting by ratio dominates; the selection pass is linear.

P5

Huffman coding is applied to 4 symbols of equal frequency. The length of each codeword is:

  • A) 1 bit
  • B) 2 bits
  • C) 3 bits
  • D) Varies from 1 to 3 bits
Show answer & explanation

Answer: B) 2 bits

Merging pairs yields a perfectly balanced tree of depth 2, so every code has 2 bits.

P6

Which of the following is NOT a greedy algorithm?

  • A) Dijkstra
  • B) Kruskal
  • C) Prim
  • D) Floyd–Warshall
Show answer & explanation

Answer: D) Floyd–Warshall

Floyd–Warshall is dynamic programming over intermediate vertices; the others make irrevocable locally optimal choices.

P7

The frequencies 1, 1, 2, 3, 5, 8 are Huffman-coded. The total cost (sum of frequency × depth) is:

  • A) 40
  • B) 45
  • C) 50
  • D) 55
Show answer & explanation

Answer: B) 45

Merges: 1+1 = 2, 2+2 = 4, 3+4 = 7, 5+7 = 12, 8+12 = 20. Sum = 2 + 4 + 7 + 12 + 20 = 45.

P8

The exchange argument is used to prove which property of a greedy algorithm?

  • A) Time complexity
  • B) Greedy-choice property
  • C) Overlapping subproblems
  • D) Termination
Show answer & explanation

Answer: B) Greedy-choice property

Swapping an optimal solution element for the greedy choice shows that an optimal solution containing the greedy choice exists.

P9

Jobs (deadline, profit): J1(2, 100), J2(1, 19), J3(2, 27), J4(1, 25), J5(3, 15), each taking unit time. The maximum profit by the greedy job sequencing algorithm is:

  • A) 127
  • B) 142
  • C) 152
  • D) 186
Show answer & explanation

Answer: B) 142

J1 takes slot 2, J3 takes slot 1, J5 takes slot 3; J4 and J2 find slot 1 occupied. Profit 100 + 27 + 15 = 142.

P10

Kruskal algorithm detects cycles efficiently using which data structure?

  • A) Stack
  • B) Queue
  • C) Disjoint-set (Union-Find)
  • D) Binary search tree
Show answer & explanation

Answer: C) Disjoint-set (Union-Find)

Find checks whether two endpoints are already in the same component; Union merges components when an edge is accepted.

Topic FAQs

How do I know if a greedy algorithm is correct?

Show the greedy-choice property (usually by an exchange argument) and optimal substructure; otherwise find a small counterexample.

Why is Huffman coding optimal among prefix codes?

Merging the two least frequent symbols first is safe by the exchange argument: they can be made deepest siblings in some optimal tree.

Is Dijkstra a greedy algorithm?

Yes, it permanently settles the closest unsettled vertex; this is correct only when edge weights are non-negative.

Does Kruskal always give the same tree as Prim?

Both give an MST of the same total weight; with distinct weights the tree is identical, with ties the edge sets may differ.

Quick revision · 10 cards

10 flashcards — Greedy Algorithms

Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.

Q1 What two properties must a problem have for a greedy algorithm to be correct?
Q2 What is the exchange argument in proofs of greedy algorithms?
Q3 Which criterion makes activity selection optimal and what is its time complexity?
Q4 Why does greedy by ratio solve fractional knapsack but not 0/1 knapsack?
Q5 How does the Huffman algorithm build its code tree?
Q6 How many internal nodes and total nodes does a Huffman tree for n symbols have?
Q7 How can you compute the total Huffman-coded size without finding each code?
Q8 What are the cut property and cycle property of minimum spanning trees?
Q9 What are the time complexities of Kruskal and Prim algorithms?
Q10 Give an example showing that greedy coin change can fail.