Skip to content
GATEiit

GATE CSE · Algorithms

Algorithm design techniques: greedy, dynamic programming and divide-and-conquer

Divide-and-conquer, greedy and dynamic programming: when each one works, the standard problems for each (Huffman coding, fractional knapsack, activity selection, LCS, 0/1 knapsack, matrix chain), and how GATE asks for their costs and answers.

Before you start

This topic comes before: Graph traversals, minimum spanning trees and shortest paths

Concept notes

1. Divide and conquer

Divide the problem into smaller independent subproblems, conquer them recursively, and combine the answers. Running time is a recurrence T(n)=a T(n/b)+f(n), where f(n) is the divide plus combine cost.

Problem Recurrence Time
Binary search T(n/2)+1 Θ(log⁡n)
Merge sort 2T(n/2)+n Θ(nlog⁡n)
Quick sort (balanced) 2T(n/2)+n Θ(nlog⁡n)
Fast power xn T(n/2)+1 Θ(log⁡n) multiplications
Karatsuba multiplication 3T(n/2)+n Θ(nlog⁡23)≈n1.585
Strassen matrix multiplication 7T(n/2)+n2 Θ(nlog⁡27)≈n2.81
Closest pair of points 2T(n/2)+n Θ(nlog⁡n)

Max and min together: compare elements in pairs, then the larger against the current max and the smaller against the current min. This takes ⌈3n/2⌉−2 comparisons, against 2n−2 for the naive method.

Divide and conquer suits problems whose subproblems do not overlap. If the same subproblem repeats (as in naive Fibonacci), use DP instead.

2. Greedy algorithms

A greedy algorithm makes the locally best choice at each step and never revisits it. It is correct only when the problem has:

  • the greedy-choice property: some optimal solution begins with the greedy choice, and
  • optimal substructure: after the choice, what remains is a smaller instance of the same problem.
Problem Greedy rule Time
Activity selection earliest finish time first O(nlog⁡n)
Fractional knapsack highest value/weight ratio first O(nlog⁡n)
Huffman coding merge the two least frequent O(nlog⁡n)
Optimal merge pattern merge the two smallest files O(nlog⁡n)
Job sequencing with deadlines highest profit first, latest free slot O(n2) simple version
MST (Kruskal, Prim), Dijkstra lightest safe edge / nearest vertex O(Elog⁡V)

Greedy fails for 0/1 knapsack and for coin change with arbitrary coins (coins 1, 3, 4 and amount 6: greedy gives 4+1+1, the best is 3+3).

Huffman coding: the total encoded length equals the sum of all merge weights. Codes are prefix-free; frequent symbols get short codes.

50e:2030d:1218c:810a:4b:601010101e = 0, d = 10, c = 110a = 1110, b = 1111total = 108 bits
Huffman tree for a:4, b:6, c:8, d:12, e:20 (left edge 0, right edge 1)

3. Dynamic programming

Dynamic programming (DP) solves problems with overlapping subproblems and optimal substructure. Write a recurrence, then compute each subproblem once:

  • Memoization (top-down): recursion plus a table; solves only the subproblems reached.
  • Tabulation (bottom-up): fill the table in an order where dependencies come first.

Time = (number of subproblems) × (work per subproblem).

Problem Recurrence (core) Time
LCS of lengths m,n L[i][j]=L[i−1][j−1]+1 if xi=yj, else max⁡(L[i−1][j],L[i][j−1]) Θ(mn)
0/1 knapsack, capacity W K[i][w]=max⁡(K[i−1][w], vi+K[i−1][w−wi]) Θ(nW)
Matrix chain, n matrices m[i][j]=min⁡k(m[i][k]+m[k+1][j]+pi−1pkpj) Θ(n3)
Subset sum to S T[i][s]=T[i−1][s]∨T[i−1][s−ai] Θ(nS)
Edit distance min of insert, delete, replace Θ(mn)
Longest increasing subsequence L[i]=1+max⁡j<i, aj<aiL[j] Θ(n2)
Floyd–Warshall dk[i][j]=min⁡(dk−1[i][j], dk−1[i][k]+dk−1[k][j]) Θ(V3)

Θ(nW) for knapsack is pseudo-polynomial: it is polynomial in the value W, but exponential in the number of bits used to write W.

For matrix chain, multiplying a p×q matrix by a q×r matrix costs pqr scalar multiplications.

4. Choosing the technique

Question to ask If yes
Do subproblems repeat? DP (or memoized recursion)
Are subproblems independent and of size n/b? Divide and conquer
Can a simple local rule be proved safe (exchange argument)? Greedy

How they compare:

  • Greedy makes one choice and moves on; DP tries every choice for a subproblem and keeps the best. So DP is correct whenever greedy is, but usually slower.
  • Divide and conquer and DP both use recursion; DP adds a table because the same subproblem comes up again.
  • Fractional knapsack is greedy; 0/1 knapsack needs DP. Shortest paths with non-negative weights: greedy (Dijkstra). With negative edges: DP (Bellman–Ford, Floyd–Warshall).

To prove a greedy rule wrong, find one small counterexample. To prove it right, use an exchange argument: take any optimal solution, swap in the greedy choice, and show it is no worse.

Formulas to remember

Matrix product cost
(p×q)(q×r)⇒pqr multiplications
Matrix chain DP
m[i][j]=min⁡i≤k<j(m[i][k]+m[k+1][j]+pi−1pkpj)
LCS DP
0/1 knapsack DPSecond option only if wi≤w
K[i][w]=max⁡(K[i−1][w], vi+K[i−1][w−wi])
Huffman total length
∑ifi⋅depthi=sum of all merge weights
Strassen
T(n)=7T(n/2)+Θ(n2)=Θ(nlog⁡27)
Max and min together
⌈3n2⌉−2 comparisons

Common mistakes

  • Using greedy by value/weight for 0/1 knapsack; it is optimal only when fractions are allowed.
  • Sorting by start time or by duration for activity selection; the safe rule is earliest finish time.
  • In Huffman coding, merging the two largest weights, or forgetting that total bits equals the sum of merge weights.
  • Calling the Θ(nW) knapsack DP polynomial; it is pseudo-polynomial.
  • In matrix chain, using pi−1pipj instead of pi−1pkpj for the split cost.
  • Using plain recursion where subproblems overlap; without a table the time can become exponential.

Worked examples

Try each step yourself, then reveal the working.

Example 1: Huffman code lengths and total bits

numerical

Symbols and frequencies: a 4, b 6, c 8, d 12, e 20. Build a Huffman code. Find each code length, the total bits, and the average bits per symbol.

  1. Step 1: Merge the two smallest weights repeatedly.

    Try it on paper first.

Example 2: Fractional vs 0/1 knapsack

numerical

Capacity 20. Items (weight, value): A (10, 60), B (5, 40), C (15, 45), D (8, 32). Find the best value for the fractional knapsack and for the 0/1 knapsack.

  1. Step 1: Compute value per unit weight.

    Try it on paper first.

Example 3: Matrix chain multiplication

numerical

Matrices A1 (5 × 4), A2 (4 × 6), A3 (6 × 2), A4 (2 × 7). Find the minimum number of scalar multiplications to compute A1A2A3A4.

  1. Step 1: Fill the chains of length 2.

    Try it on paper first.

Example 4: Why greedy coin change fails

conceptual

Coins of value 1, 3 and 4 are available in any number. Does picking the largest coin first always use the fewest coins?

  1. Step 1: Try amount 6 greedily.

    Try it on paper first.

Previous year questions

14 official GATE CSE questions on this topic, newest first.

Practise these 14 PYQs →

Topic test

10 questions: up to 4 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.

Mark as mastered

Loading your progress…

My revision notes

Notes written by the GATEiit team against the official GATE CSE syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.