Computer Science and IT‹›⌂ 0:00 studied

Module 6 · 15 min read · Free chapter

Greedy algorithms and minimum spanning trees

In short

A greedy algorithm makes the best-looking choice at each step and never undoes it, so it is optimal only for some problems. It works for activity selection by earliest finish time, fractional knapsack by value per weight and Huffman coding. Kruskal and Prim both build a minimum spanning tree with V − 1 edges.

What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: change at the shop and pipes between villages

A shopkeeper has to return ₹18 in change and has coins of ₹10, ₹5, ₹2 and ₹1. Without thinking much, he gives the largest coin that fits, ₹10, then ₹5, then ₹2 and finally ₹1. He uses 4 coins, and for these coins that is the fewest possible.

That habit of "take the best-looking piece now and never look back" is called greedy. It is fast and simple, but it is not always right. If the coins were ₹1, ₹3 and ₹4 and the change were ₹6, greed would give 4+1+14 + 1 + 1, three coins, while 3+33 + 3 needs only two.

Now picture a block office that must bring piped water to six villages. Each possible pipe route between two villages has a cost, and the office wants every village connected at the least total cost. It needs no loops, because a loop means one pipe is wasted, so the answer is a tree that spans all the villages.

Why it matters. This second problem, the minimum spanning tree, is one where a greedy method is provably correct. Road, cable, power-grid and network designers solve it every day, and GATE asks about it almost every year.

When greed works, and activity selection

A greedy algorithm makes one choice at a time, picks whatever looks best by a fixed rule, and never undoes a choice. For this to give the best answer, the problem needs two properties. The greedy-choice property says that some optimal solution starts with the greedy choice, and optimal substructure says that after that choice, the rest of an optimal solution is an optimal solution of the smaller problem that remains.

Proving a greedy rule correct usually takes an exchange argument. Take any optimal solution, swap its first choice for the greedy choice, and show the result is no worse. Showing a rule wrong takes just one counterexample, like the ₹1, ₹3, ₹4 coins.

Activity selection is the classic case. Several groups want to book one seminar hall, and each booking has a start and a finish time. We want to accept the largest number of bookings that do not overlap.

Three rules look sensible, but only one works. "Earliest start first" fails, because a booking from 9 to 16 hours starts first and blocks the whole day. "Shortest first" fails too: with bookings 1 to 5, 4 to 7 and 6 to 10, the shortest one, 4 to 7, clashes with both others, so it allows 1 booking where 2 are possible.

The rule that works is earliest finish first. Sort the bookings by finish time, take the first, and then keep taking the next booking that starts no earlier than the last chosen one finishes. Finishing early leaves the most room for the rest, and the exchange argument turns that intuition into a proof.

Worked example. The bookings are P (9 to 11), Q (10 to 12), R (11 to 13), S (12 to 14), T (13 to 15) and U (9 to 16), already in order of finish time. Take P; Q starts at 10, before 11, so skip it; take R; S starts at 12, before 13, so skip it; take T; skip U. The answer is 3 bookings, P, R and T, and the work is O(nlog⁡n)O(n \log n) for sorting and O(n)O(n) for the scan.

Why it matters. Most greedy questions in GATE are really asking "which rule is correct?". Learning to test a rule with a small counterexample saves time and marks.

Fractional knapsack and job sequencing

A trader has a bag that holds 10 kg and three sacks of goods: A weighs 6 kg and is worth ₹30, B weighs 5 kg and is worth ₹20, and C weighs 5 kg and is worth ₹20. Which goods should go in the bag to carry the most value?

In the fractional knapsack problem the trader may take part of a sack, like pouring out some rice. The greedy rule is to sort by value per kg and fill the bag in that order. A gives ₹5 per kg and B and C give ₹4 per kg, so take all of A for ₹30 and then 4 kg of B for ₹16, a total of ₹46, which is the best possible.

In the 0/1 knapsack problem each sack is taken whole or not at all. The same greedy rule takes A first, and then neither B nor C fits, so it ends with ₹30. But B and C together weigh 10 kg and are worth ₹40, so greedy fails here, and the 0/1 version needs dynamic programming.

Job sequencing with deadlines is another greedy problem. Each job takes one unit of time on a single machine, has a deadline and earns its profit only if finished by the deadline. The rule is to consider jobs in decreasing order of profit and place each one in the latest free slot at or before its deadline, so that earlier slots stay free for jobs with tighter deadlines.

Worked example. The jobs, as (deadline, profit), are J1 (2, 100), J2 (1, 19), J3 (2, 27), J4 (1, 25) and J5 (3, 15). In profit order J1 goes to slot 2 and J3, whose slot 2 is taken, goes to slot 1. J4 and J2 both have deadline 1, which is full, so they are skipped, and J5 goes to slot 3, giving a total profit of 100+27+15=142100 + 27 + 15 = 142.

Checking slots one by one gives O(n2)O(n^2) time in the worst case. Keeping the free slots in a union-find structure, where each slot points to the nearest free slot to its left, brings this close to O(nlog⁡n)O(n \log n), with the sort as the main cost.

Why it matters. The knapsack pair is the cleanest example in the syllabus of how one small change in a problem decides whether greed works. Exams love to give the same items and ask for both answers.

Huffman coding

Suppose a message uses only five symbols, A, B, C, D and E. A fixed-length code needs 3 bits per symbol, because 2 bits give only 4 patterns. But if A appears far more often than E, it makes sense to give A a short code and E a long one, as Morse code does with letters.

Variable-length codes have one danger: the receiver must know where one codeword ends. The fix is a prefix code, in which no codeword is the beginning of another. Then the bits can be read left to right and each codeword is recognised the moment it is complete.

Huffman's greedy rule builds the best prefix code. Put every symbol in a min-priority queue keyed by frequency. Repeatedly remove the two nodes with the smallest frequencies, join them under a new node whose frequency is their sum, and put the new node back; after n−1n - 1 merges one tree remains, and reading 0 for a left edge and 1 for a right edge gives each symbol's code.

Worked example. In 100 symbols the frequencies are A 40, B 25, C 20, D 10 and E 5. First E and D merge into 15; then 15 and C merge into 35; then B and 35 merge into 60; finally A and 60 merge into 100. One labelling gives A = 0, B = 10, C = 111, D = 1101 and E = 1100.

The total length is 40×1+25×2+20×3+10×4+5×4=21040 \times 1 + 25 \times 2 + 20 \times 3 + 10 \times 4 + 5 \times 4 = 210 bits, an average of 2.1 bits per symbol. The fixed-length code would need 300 bits, so Huffman saves 30 percent here. A quick check of the total: it always equals the sum of the frequencies of all the merged nodes, 15+35+60+100=21015 + 35 + 60 + 100 = 210.

With a binary heap, each of the n−1n - 1 merges takes O(log⁡n)O(\log n), so the whole method runs in O(nlog⁡n)O(n \log n). Ties can be broken either way; the codes may change, but the total length stays the same.

Why it matters. Huffman's idea sits inside file compression formats and image and audio coding. GATE questions usually give frequencies and ask for the average code length or the code of one symbol.

Minimum spanning trees and the cut property

Take a connected, undirected graph with weights on its edges. A spanning tree is a set of edges that connects all VV vertices with no cycle, and every spanning tree has exactly V−1V - 1 edges. A minimum spanning tree (MST) is a spanning tree whose total weight is as small as possible.

A graph can have a huge number of spanning trees. The complete graph on nn labelled vertices has nn−2n^{n-2} of them, which is 16 for n=4n = 4 and already 100,000,000 for n=10n = 10. So we cannot try them all, and we need a rule that picks edges safely.

The cut property is that rule. Split the vertices into any two non-empty groups SS and V−SV - S; this split is called a cut, and an edge with one end in each group crosses the cut. The lightest edge crossing any cut belongs to some MST, and if it is the only lightest one, it belongs to every MST.

The reason is an exchange argument. If an MST left out that lightest edge e, adding e would create a cycle, and that cycle must cross the cut again through some other edge f that is at least as heavy. Removing f gives a spanning tree that is no heavier, so some MST contains e.

The cycle property is the mirror image. If an edge is the unique heaviest edge on some cycle, no MST contains it, because it can always be swapped for a lighter edge of that cycle.

Uniqueness. If all edge weights are distinct, the MST is unique. The converse is false: a graph with equal weights can still have only one MST, for example when the graph is itself a tree.

Two more facts often appear as statements to judge. Adding the same constant to every edge weight does not change which trees are minimum, because every spanning tree has the same number of edges, V−1V - 1. But the path between two vertices inside an MST is not necessarily their shortest path in the graph.

Why it matters. Both Kruskal's and Prim's algorithms are just two different ways of applying the cut property again and again. GATE often asks whether a given edge must, may or cannot be in an MST, and the cut and cycle properties answer this directly.

Kruskal's and Prim's algorithms

We will run both algorithms on one graph with vertices A to E and edges AB = 4, AC = 1, BC = 2, BD = 5, CD = 8, CE = 9 and DE = 3. Both will find the same total, but they add the edges in different orders, and exams often ask for that order.

Kruskal's algorithm looks at edges, not vertices. Sort all edges by weight, start with every vertex as its own little tree, and take each edge in order if it joins two different trees; skip it if both ends are already in the same tree, because it would form a cycle. Stop after V−1V - 1 edges.

On our graph the sorted edges are AC 1, BC 2, DE 3, AB 4, BD 5, CD 8 and CE 9. Kruskal takes AC, BC and DE, then rejects AB because A and B are already joined through C, and then takes BD, which links the groups {A, B, C} and {D, E}. That makes 4=V−14 = V - 1 edges with total weight 1+2+3+5=111 + 2 + 3 + 5 = 11.

The cycle test uses a union-find (disjoint-set) structure. Find(xx) returns the representative of xx's group, and Union(xx, yy) merges two groups. With union by rank and path compression, each operation costs almost constant amortised time, so the sort dominates and Kruskal runs in O(Elog⁡E)O(E \log E), which equals O(Elog⁡V)O(E \log V) because E≤V2E \le V^2.

sort edges by weight
for each vertex v: make_set(v)
for each edge (u, v) in sorted order:
    if find(u) != find(v):
        add (u, v) to the tree
        union(u, v)

Prim's algorithm looks at one growing tree. Start from any vertex and repeatedly add the lightest edge that joins a tree vertex to a vertex outside the tree. A priority queue keeps, for each outside vertex, the weight of its cheapest edge to the tree.

From A, Prim first takes AC 1. From {A, C} the cheapest outgoing edge is CB 2, and from {A, B, C} it is BD 5, since CD is 8 and CE is 9. From {A, B, C, D} it is DE 3, so Prim adds AC, CB, BD and DE, again with total 11.

With a binary heap, Prim takes O((V+E)log⁡V)=O(Elog⁡V)O((V + E) \log V) = O(E \log V). With an adjacency matrix and a plain array of best weights, each of the VV steps scans VV entries, giving O(V2)O(V^2), which is better for dense graphs where EE is close to V2V^2. With a Fibonacci heap the time drops to O(E+Vlog⁡V)O(E + V \log V).

Why it matters. Kruskal suits sparse graphs given as edge lists, and Prim suits dense graphs given as matrices. GATE asks for the order of edges, the total weight and the running time under a stated data structure, so trace both carefully on small graphs.

Descriptive lens: how written papers ask this

Written papers for IT officer posts, state Assistant Programmer exams and university tests ask about greedy methods and MSTs in four ways:

  1. Explain the greedy method, its two properties and one example where it fails.
  2. Apply a greedy algorithm to given data, such as Huffman frequencies, knapsack items or job deadlines.
  3. Trace Kruskal's or Prim's algorithm on a graph and list the edges in the order they are added.
  4. Prove a property, such as the cut property, or compare Kruskal and Prim on time and suitability.

Practice questions (our own, not previous-year questions).

  1. Explain why the greedy rule by value per weight is optimal for fractional knapsack but not for 0/1 knapsack, with an example. (10 marks)
  2. Build a Huffman code for frequencies 30, 25, 20, 15 and 10 and find the average code length. (10 marks)
  3. State and prove the cut property, and explain how Kruskal's algorithm uses it. (15 marks)

Answer plan for question 3.

  • Define a cut of a connected weighted graph as a split of its vertices into two non-empty sets, and define a crossing edge.
  • State that the lightest edge e crossing any cut belongs to some minimum spanning tree.
  • Suppose an MST T does not contain e, and note that adding e to T creates exactly one cycle.
  • Argue that this cycle must cross the cut a second time through another edge f, whose weight is at least that of e.
  • Show that T plus e minus f is a spanning tree with weight no more than T, so it is also an MST and contains e.
  • Explain that when Kruskal adds the lightest edge joining two different trees, the cut between one of those trees and the rest of the graph makes that edge safe.

Quick revision

  • A greedy algorithm takes the best-looking choice at each step and never undoes it.
  • Greedy is correct only with the greedy-choice property and optimal substructure, and coins {1, 3, 4} for amount 6 show it can fail.
  • Activity selection is solved by picking the earliest-finishing compatible activity each time.
  • Fractional knapsack is solved by value per weight, but 0/1 knapsack needs dynamic programming.
  • Job sequencing places each job, in profit order, in the latest free slot before its deadline.
  • Huffman coding merges the two lowest frequencies n−1n - 1 times and runs in O(nlog⁡n)O(n \log n).
  • A spanning tree on VV vertices has V−1V - 1 edges, and KnK_n has nn−2n^{n-2} spanning trees.
  • The lightest edge across any cut is safe, and the unique heaviest edge on a cycle is never in an MST.
  • Kruskal runs in O(Elog⁡V)O(E \log V) with union-find, and Prim runs in O(Elog⁡V)O(E \log V) with a binary heap or O(V2)O(V^2) with an array.
  • Distinct edge weights give a unique MST.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 14 answered

  1. A greedy algorithm:

  2. With coins {1, 3, 4}, the greedy method (largest coin first) makes change for 6 using:

  3. For activity selection, the greedy rule that is always optimal is to pick next the activity with the:

  4. Capacity 10; items (weight, value): A (6, 30), B (5, 20), C (5, 20). The optimal fractional knapsack value is:

  5. For the same items as a 0/1 knapsack with capacity 10, greedy by value per weight gives 30. The optimal value is:

  6. Unit-time jobs (deadline, profit): J1 (2, 100), J2 (1, 19), J3 (2, 27), J4 (1, 25), J5 (3, 15). The maximum total profit is:

  7. Symbols with frequencies 40, 25, 20, 10 and 5 are Huffman coded. The total number of bits for these 100 symbols is:

  8. In a prefix code:

  9. A spanning tree of a connected graph with VV vertices has exactly:

  10. The number of spanning trees of the complete graph K4K_4 is:

  11. An edge e is the unique heaviest edge on some cycle of a connected weighted graph. Then e is:

  12. If 5 is added to the weight of every edge of a connected graph, the minimum spanning trees:

  13. On the graph AB = 4, AC = 1, BC = 2, BD = 5, CD = 8, CE = 9, DE = 3, the fourth edge Kruskal adds is:

  14. Prim's algorithm implemented with an adjacency matrix and a simple array of keys runs in:

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

Why does greedy fail for 0/1 knapsack?

Items cannot be split, so taking the best ratio first can leave unused capacity. With capacity 10 and items (6, 30), (5, 20), (5, 20), greedy gets 30 but the best is 40.

What is the difference between Kruskal and Prim?

Kruskal sorts all edges and adds the lightest edge that makes no cycle. Prim grows one tree from a start vertex, adding the lightest edge that leaves it.

Is the minimum spanning tree unique?

It is unique when all edge weights are distinct. With equal weights there can be several trees of the same minimum total weight.

What is the time complexity of Huffman coding?

With a min-heap it is Θ(n log n) for n symbols, since there are n − 1 merges and each heap operation costs Θ(log n).

More in this module: Algorithms

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Algorithms (IIT Kharagpur, 106105164): greedy algorithms and minimum spanning trees
  3. NPTEL Programming, Data Structures and Algorithms (CMI, 106106145): greedy algorithms, Prim, Kruskal, union-find, Huffman coding