Chapter 5

Divide-and-conquer and greedy choicesCS

A design technique is justified by what makes its subproblems or choices safe. Divide-and-conquer combines recursively solved parts; greedy methods commit to a locally best choice only when an exchange or cut argument supports it.

5.1 Design invariantsCS

Past papers · CS 2014–2026 (23 papers): 3 questions, 4 marks

TechniqueWhat to identifyTypical applications
Divide-and-conquerSmaller inputs, base case, combine costMergesort, quicksort, selection
GreedyA safe irrevocable choice and a preserved feasible optimumEarliest-finish activities, Huffman, Prim, Kruskal, Dijkstra
Dynamic programmingA state sufficient for future choices and an acyclic dependency orderKnapsack, LCS, matrix chains, Floyd–Warshall

Optimal substructure alone does not justify a greedy algorithm. For a proposed greedy rule, replace the first choice of an optimum by the greedy choice and show feasibility and value do not worsen. If this fails, seek a counterexample or a richer state. Backtracking explores choices and undoes them, typically by DFS; it does not guarantee polynomial time.

5.2 Divide-and-conquer arithmeticCS

Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks

Reusing a half-size answer matters: computing the same recursive power twice changes the recurrence. Count arithmetic operations here; arbitrary-precision bit costs require a different model.

For exponent bits processed most significant first, start z=1z=1 and update z←z2z\leftarrow z^2, then z←zaz\leftarrow za if the bit is 11. After any prefix, z=aprefix valuez=a^{\text{prefix value}}. Reduce after each operation for modular exponentiation. For a positive exponent with beb_e bits this version makes be+popcount⁡(e)b_e+\operatorname{popcount}(e) multiplications, including the initial square of 11; versions skipping the leading bit have different exact counts.

Strassen's seven products can be remembered through the following recipe. For block matrices with entries Aij,BijA_{ij},B_{ij}, define P1=(A11+A22)(B11+B22)P_1=(A_{11}+A_{22})(B_{11}+B_{22}), P2=(A21+A22)B11P_2=(A_{21}+A_{22})B_{11}, P3=A11(B12−B22)P_3=A_{11}(B_{12}-B_{22}), P4=A22(B21−B11)P_4=A_{22}(B_{21}-B_{11}), P5=(A11+A12)B22P_5=(A_{11}+A_{12})B_{22}, P6=(A21−A11)(B11+B12)P_6=(A_{21}-A_{11})(B_{11}+B_{12}), P7=(A12−A22)(B21+B22)P_7=(A_{12}-A_{22})(B_{21}+B_{22}). Recombine as C11=P1+P4−P5+P7C_{11}=P_1+P_4-P_5+P_7, C12=P3+P5C_{12}=P_3+P_5, C21=P2+P4C_{21}=P_2+P_4, C22=P1−P2+P3+P6C_{22}=P_1-P_2+P_3+P_6.

5.3 Interval selection and deadlinesCS

For maximum cardinality of compatible intervals on one resource, sort by increasing finish time and repeatedly take the next compatible interval. Represent an interval as [si,fi)[s_i,f_i) so that a finish at time tt is compatible with a start at tt. Assume si<fis_i<f_i.

Objective and assumptionsGreedy choiceTrap
Most mutually compatible intervalsEarliest finishEarliest start or shortest duration need not work
Maximum profit, unit-time jobs, integer deadlines, all available initiallyDescending profit; place each accepted job in the latest free slot at or before its deadlineVariable job durations invalidate this rule
Minimum maximum lateness, all jobs available initially, one machine, no preemptionEarliest deadlineDoes not minimize number of late jobs in general

For the unit-job rule, slots are 1,…,min⁡(n,max⁡di)1,\ldots,\min(n,\max d_i), job ii finishes at its assigned slot and must satisfy slot ≤di\le d_i. Ignore nonpositive-profit jobs when selection is optional. A direct scan of slots costs O(n2)O(n^2) after sorting; a disjoint-set slot structure can improve this.

5.4 Fractional knapsackCS

Sort by value per unit weight, then take as much of each item as fits. This applies when fractions are allowed and values add proportionally. An exchange of equal weight from a lower-density item to an available higher-density item cannot reduce value.

5.5 Huffman coding and optimal mergingCS

Past papers · CS 2014–2026 (23 papers): 3 questions, 6 marks

Repeatedly combine the two smallest current weights and reinsert their sum. A min-heap implements the process in O(nlog⁡n)O(n\log n) time. The resulting binary tree minimizes total weighted leaf depth; the binary digits on branches may be exchanged without changing the cost.

For a binary prefix code with lengths ℓi\ell_i, Kraft's condition is ∑i2−ℓi≤1\sum_i2^{-\ell_i}\le1; it is also sufficient for the existence of some binary prefix code with those lengths. With at least two positive-probability symbols, Huffman gives H≤ℓˉ<H+1H\le\bar\ell<H+1, where H=−∑ipilog⁡2piH=-\sum_i p_i\log_2 p_i is entropy in bits/symbol. A one-symbol alphabet needs an explicit empty-code versus one-bit convention. Equal frequencies allow multiple optimal trees and sometimes different length assignments; compare cost, not a unique bit pattern.

Last-minute recall

  • Prove a greedy choice safe before applying it repeatedly.
  • Optimal substructure is shared by many methods; it is not a greedy proof.
  • Compute and reuse the half-power once.
  • Interval compatibility here includes touching endpoints.
  • Unit-time job scheduling uses the latest available feasible slot.
  • Density is exact for fractional, not general 0/1, knapsack.
  • Huffman repeatedly takes the two smallest current weights.
  • Merge movements and worst comparisons differ by the number of merges.

Revise offline: the whole Algorithms handbook as one PDF

52 pages · 2.6 MBFree to read online. Sign in to download the PDF.We save the handbook, version and request time in My downloads. Privacy policy

All chapters · Corrections