Module 6 · 15 min read · Free chapter
Dynamic programming
Dynamic programming solves a problem with optimal substructure and overlapping subproblems by storing each subproblem's answer once. Its running time is the number of subproblems times the work for each. 0/1 knapsack takes Θ(nW), LCS of lengths m and n takes Θ(mn), and matrix chain multiplication takes Θ(n³).
Start from zero: climbing the ghat steps
A child at a river ghat climbs the steps either one at a time or two at a time. In how many different ways can she climb 10 steps? To reach step 10, her last move came either from step 9 or from step 8. So the number of ways for 10 is the ways for 9 plus the ways for 8.
That rule, , is easy, but a careless recursion repeats the same work again and again. To get it computes twice, three times, and so on, and the total grows exponentially. A sensible child would write each answer in a notebook: 1 way for one step, 2 for two, then 3, 5, 8, 13, 21, 34, 55 and finally 89.
This "solve each small problem once and write it down" habit is dynamic programming, often shortened to DP. It turns many exponential recursions into fast table-filling. The word "programming" here is old usage and means planning with a table, not writing code.
Why it matters. Spell checkers, DNA matching, route planning, budget allocation and compilers all use DP. GATE asks DP questions every year, usually as a table to fill or a recurrence to choose.
The two properties, memoisation and tabulation
DP works when a problem has two properties. Optimal substructure means an optimal answer is built from optimal answers to smaller subproblems. Overlapping subproblems means the same smaller subproblems come up again and again, so storing their answers saves real work.
Divide and conquer also has the first property, but its subproblems are independent: merge sort never sorts the same half twice. That is the key difference. When subproblems repeat, use DP; when they do not, plain recursion is already efficient.
Take Fibonacci: , and . The plain recursion makes calls, so computing makes 15 calls, and the count grows like with . There are only different subproblems, to , so all that extra work is repetition.
There are two ways to store answers. Memoisation keeps the recursion but checks a table first: if is already known, it is returned at once, otherwise it is computed and stored. Tabulation drops the recursion and fills the table from the bottom: , , and so on up to .
fib(n): // tabulation
if n < 2: return n
a = 0; b = 1
for i = 2 to n:
c = a + b; a = b; b = c
return b
Both versions take time. The tabulated version above keeps only the last two values, so it needs extra space, while memoisation needs a table and a recursion stack. On the other hand, memoisation computes only the subproblems the answer actually needs, which helps when the table is large but sparsely used.
A simple rule gives the running time of any DP. Time = number of distinct subproblems times the work per subproblem. For Fibonacci that is , and the same rule works for every example in this chapter.
Why it matters. Almost every DP question reduces to three choices: what a subproblem means, what the recurrence is, and in what order to fill the table. Getting the first one right usually makes the rest easy.
0/1 knapsack
A courier can carry at most kilograms and has parcels, where parcel weighs and pays rupees. Each parcel is taken whole or left behind, so this is the 0/1 knapsack problem. Greedy by value per kilogram fails here, so we need DP.
Define as the best value using only the first parcels with capacity w. For parcel there are two choices. Leave it, and the best is ; take it, which is possible only if , and the best is . So , with .
Worked example. Let with parcels (weight, value) 1: (2, 3), 2: (3, 4), 3: (4, 5) and 4: (5, 6). Filling row by row gives the table below. For instance, , which means taking parcels 1 and 2.
| Items used | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| none | 0 | 0 | 0 | 0 | 0 | 0 |
| parcel 1 | 0 | 0 | 3 | 3 | 3 | 3 |
| parcels 1–2 | 0 | 0 | 3 | 4 | 4 | 7 |
| parcels 1–3 | 0 | 0 | 3 | 4 | 5 | 7 |
| parcels 1–4 | 0 | 0 | 3 | 4 | 5 | 7 |
The answer is . To find which parcels were taken, walk back from the last cell: if , parcel was left, otherwise it was taken and w drops by . Here the walk finds parcels 2 and 1.
The table has cells and each takes , so the time is . This looks polynomial, but it is called pseudo-polynomial, because is a number in the input and writing it takes only about bits. If doubles in size every time we add one bit, the work can grow exponentially in the input length.
Why it matters. Knapsack is the model for budget, cargo and investment choices. It also shows the difference between polynomial in the value of a number and polynomial in its length, which is the doorway to NP-completeness.
Comparing strings: LCS and edit distance
A subsequence keeps some characters of a string in order but may skip others, so GAT is a subsequence of GREAT. The longest common subsequence (LCS) of two strings is the longest string that is a subsequence of both. File-comparison tools and DNA analysis use it to show what two versions have in common.
Let be the LCS length of the first characters of X and the first characters of Y. If the last characters match, , they can end the common subsequence, so . Otherwise one of them is not used, so . The first row and column are 0.
Worked example. Take X = GATE and Y = GREAT. The matches G–G, A–A and T–T sit on a rising diagonal, but E in GATE comes after T while E in GREAT comes before A, so E cannot join them. The last cell is , and tracing the diagonal arrows back spells GAT.
The table has cells, each filled in , so LCS takes time and space. If only the length is needed, keeping two rows is enough, which cuts the space to .
Edit distance asks a related question: what is the fewest single-character insertions, deletions and substitutions that turn X into Y? Spell checkers use it to suggest the nearest real word. Let be the distance between the first characters of X and the first of Y, with and .
The last step is a deletion, an insertion or a substitution, which gives . Here if , so matching characters cost nothing, and otherwise. For GATE and GREAT the answer is 3: keep G, insert R and E, keep A and T, and delete the final E.
Why it matters. Both problems use the same grid with three neighbours: up, left and the diagonal. Once you can fill one table, you can fill the other, and GATE often asks for a single cell value or the final length.
Matrix chain multiplication
Multiplying a matrix by a matrix takes pqr scalar multiplications. Matrix multiplication is associative, so (AB)C and give the same answer, but they can cost very different amounts.
Worked example. Let A be , B be and C be . For (AB)C, first AB costs and gives a matrix, and then multiplying by C costs , so the total is 2,500. For , BC costs and then A times BC costs , so the total is 9,000.
With more matrices, the number of bracketings explodes. A chain of matrices can be bracketed in ways, where C is the Catalan number: 2 ways for 3 matrices, 5 for 4 and 14 for 5. Trying them all is exponential, so we use DP.
Let matrix have size , and let be the least cost of multiplying through . The last multiplication splits the chain at some with . So , with .
The table is filled by chain length: first all chains of length 2, then length 3, and so on, because a longer chain uses only shorter ones. For dimensions , that is four matrices, the best cost is 3,000, reached by .
There are about pairs (, ), and each tries up to split points, so the time is and the space is . A second table stores the best , and reading it back prints the optimal bracketing.
Why it matters. This is the model for every "interval" DP, where a subproblem is a contiguous range and the choice is where to split it. Database query planners use the same idea to choose the order of joins.
Coin change, the DP recipe and a look at Floyd–Warshall
We saw that greedy fails to make change for 6 with coins {1, 3, 4}. DP fixes this. Let be the fewest coins that make amount , with . The last coin used is some , so .
Worked example. With coins {1, 3, 4}, the values for amounts 0 to 6 are 0, 1, 2, 1, 1, 2 and 2. For the choices are , and , that is 2, 1 and 2, so , using . Each amount checks coin types, so making amount takes time.
A different question is how many ways a sum can be made, ignoring order. Fill , then for each coin c in turn do for v from c up to . With coins {1, 2, 5} there are 4 ways to make 5: 5, , and .
Putting the coin loop outside is what stops and from being counted twice. If the amount loop is outside instead, the method counts ordered sequences, which is a different problem.
Every example in this chapter followed the same recipe:
- Define the subproblem in words, such as "the best value using the first items with capacity w".
- Write the recurrence by asking what the last choice was.
- Set the base cases, such as an empty string or zero capacity.
- Choose a fill order in which every entry's inputs are already filled.
- Read the answer from the right cell and, if needed, trace back the choices.
The same recipe also solves the all-pairs shortest path problem. In Floyd–Warshall, the subproblem is the shortest path from to that uses only vertices 1 to in between, and the table is updated once for each , so it takes . The full method is taught with graph traversal and shortest paths.
| Technique | Subproblems | Choice made | Example |
|---|---|---|---|
| Divide and conquer | independent | none, all parts are solved | Merge sort |
| Greedy | one, after a fixed choice | best-looking now | Huffman coding |
| Dynamic programming | overlapping, all stored | best over all options | 0/1 knapsack, LCS |
Why it matters. The recipe turns DP from a bag of tricks into a method. In an exam, writing the subproblem in words first prevents most wrong recurrences.
Descriptive lens: how written papers ask this
Written papers for IT officer posts, state Assistant Programmer exams and university tests ask about dynamic programming in four ways:
- Explain the two properties and contrast DP with divide and conquer and with greedy methods.
- Write the recurrence for a named problem and state its time and space.
- Fill a table for given data, such as a knapsack, an LCS or a matrix chain, and trace back the answer.
- Compare memoisation with tabulation using a small example such as Fibonacci.
Practice questions (our own, not previous-year questions).
- Explain overlapping subproblems with the Fibonacci recursion tree, and show how memoisation reduces the time from exponential to linear. (10 marks)
- Find the LCS of PATNA and PUNE by filling the table, and state the time complexity. (10 marks)
- Find the optimal bracketing for matrices of sizes , , and using dynamic programming. (15 marks)
Answer plan for question 3.
- Write the dimension list and state that is the least cost of multiplying matrices to .
- State the recurrence , with .
- Fill chains of length 2 to get , and .
- Fill chains of length 3 to get and , recording the best split points.
- Compute .
- Conclude that the optimal order is , and state that the method takes time and space.
Quick revision
- Dynamic programming needs optimal substructure and overlapping subproblems.
- Memoisation is top-down with a lookup table, and tabulation is bottom-up in a fixed fill order.
- Plain recursive Fibonacci is exponential, about , while DP makes it time with extra space.
- The running time of a DP is the number of subproblems times the work per subproblem.
- 0/1 knapsack uses and takes , which is pseudo-polynomial.
- LCS uses a match on the diagonal plus one, otherwise the larger of up and left, and takes .
- Edit distance takes the minimum of delete, insert and substitute, and GATE to GREAT is 3.
- Matrix chain uses and takes .
- Coin change by DP works for every coin system, and with coins {1, 3, 4} the amount 6 needs 2 coins.
- Floyd–Warshall is a DP over intermediate vertices and takes .