Computer Science and IT‹›⌂ 0:00 studied

Module 6 · 15 min read · Free chapter

Dynamic programming

In short

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³).

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

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, S(n)=S(n−1)+S(n−2)S(n) = S(n - 1) + S(n - 2), is easy, but a careless recursion repeats the same work again and again. To get S(10)S(10) it computes S(8)S(8) twice, S(7)S(7) 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: F(0)=0F(0) = 0, F(1)=1F(1) = 1 and F(n)=F(n−1)+F(n−2)F(n) = F(n - 1) + F(n - 2). The plain recursion makes C(n)=C(n−1)+C(n−2)+1C(n) = C(n - 1) + C(n - 2) + 1 calls, so computing F(5)F(5) makes 15 calls, and the count grows like φn\varphi^n with φ≈1.618\varphi \approx 1.618. There are only n+1n + 1 different subproblems, F(0)F(0) to F(n)F(n), so all that extra work is repetition.

There are two ways to store answers. Memoisation keeps the recursion but checks a table first: if F(k)F(k) 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: F(0)F(0), F(1)F(1), F(2)F(2) and so on up to F(n)F(n).

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 Θ(n)\Theta(n) time. The tabulated version above keeps only the last two values, so it needs Θ(1)\Theta(1) extra space, while memoisation needs a Θ(n)\Theta(n) table and a Θ(n)\Theta(n) 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 (n+1)×O(1)=Θ(n)(n + 1) \times O(1) = \Theta(n), 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 WW kilograms and has nn parcels, where parcel ii weighs wiw_i and pays viv_i 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 K[i][w]K[i][w] as the best value using only the first ii parcels with capacity w. For parcel ii there are two choices. Leave it, and the best is K[i−1][w]K[i - 1][w]; take it, which is possible only if wi≤ww_i \le w, and the best is vi+K[i−1][w−wi]v_i + K[i - 1][w - w_i]. So K[i][w]=max⁡(K[i−1][w],vi+K[i−1][w−wi])K[i][w] = \max(K[i - 1][w], v_i + K[i - 1][w - w_i]), with K[0][w]=0K[0][w] = 0.

Worked example. Let W=5W = 5 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, K[2][5]=max⁡(K[1][5],4+K[1][2])=max⁡(3,4+3)=7K[2][5] = \max(K[1][5], 4 + K[1][2]) = \max(3, 4 + 3) = 7, which means taking parcels 1 and 2.

Items used w=0w = 0 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 K[4][5]=7K[4][5] = 7. To find which parcels were taken, walk back from the last cell: if K[i][w]=K[i−1][w]K[i][w] = K[i - 1][w], parcel ii was left, otherwise it was taken and w drops by wiw_i. Here the walk finds parcels 2 and 1.

The table has (n+1)(W+1)(n + 1)(W + 1) cells and each takes O(1)O(1), so the time is Θ(nW)\Theta(nW). This looks polynomial, but it is called pseudo-polynomial, because WW is a number in the input and writing it takes only about log⁡2W\log_2 W bits. If WW 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 c[i][j]c[i][j] be the LCS length of the first ii characters of X and the first jj characters of Y. If the last characters match, xi=yjx_i = y_j, they can end the common subsequence, so c[i][j]=c[i−1][j−1]+1c[i][j] = c[i - 1][j - 1] + 1. Otherwise one of them is not used, so c[i][j]=max⁡(c[i−1][j],c[i][j−1])c[i][j] = \max(c[i - 1][j], c[i][j - 1]). 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 c[4][5]=3c[4][5] = 3, and tracing the diagonal arrows back spells GAT.

The table has (m+1)(n+1)(m + 1)(n + 1) cells, each filled in O(1)O(1), so LCS takes Θ(mn)\Theta(mn) time and Θ(mn)\Theta(mn) space. If only the length is needed, keeping two rows is enough, which cuts the space to Θ(min⁡(m,n))\Theta(\min(m, n)).

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 D[i][j]D[i][j] be the distance between the first ii characters of X and the first jj of Y, with D[i][0]=iD[i][0] = i and D[0][j]=jD[0][j] = j.

The last step is a deletion, an insertion or a substitution, which gives D[i][j]=min⁡(D[i−1][j]+1,D[i][j−1]+1,D[i−1][j−1]+t)D[i][j] = \min(D[i - 1][j] + 1, D[i][j - 1] + 1, D[i - 1][j - 1] + t). Here t=0t = 0 if xi=yjx_i = y_j, so matching characters cost nothing, and t=1t = 1 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 p×qp \times q matrix by a q×rq \times r matrix takes pqr scalar multiplications. Matrix multiplication is associative, so (AB)C and A(BC)A(BC) give the same answer, but they can cost very different amounts.

Worked example. Let A be 10×2010 \times 20, B be 20×520 \times 5 and C be 5×305 \times 30. For (AB)C, first AB costs 10×20×5=1,00010 \times 20 \times 5 = 1{,}000 and gives a 10×510 \times 5 matrix, and then multiplying by C costs 10×5×30=1,50010 \times 5 \times 30 = 1{,}500, so the total is 2,500. For A(BC)A(BC), BC costs 20×5×30=3,00020 \times 5 \times 30 = 3{,}000 and then A times BC costs 10×20×30=6,00010 \times 20 \times 30 = 6{,}000, so the total is 9,000.

With more matrices, the number of bracketings explodes. A chain of nn matrices can be bracketed in C(n−1)C(n - 1) 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 AiA_i have size pi−1×pip_{i-1} \times p_i, and let m[i][j]m[i][j] be the least cost of multiplying AiA_i through AjA_j. The last multiplication splits the chain at some kk with i≤k<ji \le k < j. So m[i][j]=min⁡i≤k<j(m[i][k]+m[k+1][j]+pi−1⋅pk⋅pj)m[i][j] = \min_{i \le k < j} (m[i][k] + m[k + 1][j] + p_{i-1} \cdot p_k \cdot p_j), with m[i][i]=0m[i][i] = 0.

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 p=10,20,5,30,10p = 10, 20, 5, 30, 10, that is four matrices, the best cost is 3,000, reached by (A1A2)(A3A4)(A_1A_2)(A_3A_4).

There are about n22\dfrac{n^2}{2} pairs (ii, jj), and each tries up to n−1n - 1 split points, so the time is Θ(n3)\Theta(n^3) and the space is Θ(n2)\Theta(n^2). A second table s[i][j]s[i][j] stores the best kk, 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 C[x]C[x] be the fewest coins that make amount xx, with C[0]=0C[0] = 0. The last coin used is some c≤xc \le x, so C[x]=1+min⁡c≤xC[x−c]C[x] = 1 + \min_{c \le x} C[x - c].

Worked example. With coins {1, 3, 4}, the values for amounts 0 to 6 are 0, 1, 2, 1, 1, 2 and 2. For x=6x = 6 the choices are C[5]C[5], C[3]C[3] and C[2]C[2], that is 2, 1 and 2, so C[6]=1+1=2C[6] = 1 + 1 = 2, using 3+33 + 3. Each amount checks kk coin types, so making amount xx takes Θ(xk)\Theta(xk) time.

A different question is how many ways a sum can be made, ignoring order. Fill W[0]=1W[0] = 1, then for each coin c in turn do W[v]=W[v]+W[v−c]W[v] = W[v] + W[v - c] for v from c up to xx. With coins {1, 2, 5} there are 4 ways to make 5: 5, 2+2+12 + 2 + 1, 2+1+1+12 + 1 + 1 + 1 and 1+1+1+1+11 + 1 + 1 + 1 + 1.

Putting the coin loop outside is what stops 2+1+1+12 + 1 + 1 + 1 and 1+2+1+11 + 2 + 1 + 1 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:

  1. Define the subproblem in words, such as "the best value using the first ii items with capacity w".
  2. Write the recurrence by asking what the last choice was.
  3. Set the base cases, such as an empty string or zero capacity.
  4. Choose a fill order in which every entry's inputs are already filled.
  5. 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 ii to jj that uses only vertices 1 to kk in between, and the table is updated once for each kk, so it takes Θ(V3)\Theta(V^3). 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:

  1. Explain the two properties and contrast DP with divide and conquer and with greedy methods.
  2. Write the recurrence for a named problem and state its time and space.
  3. Fill a table for given data, such as a knapsack, an LCS or a matrix chain, and trace back the answer.
  4. Compare memoisation with tabulation using a small example such as Fibonacci.

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

  1. Explain overlapping subproblems with the Fibonacci recursion tree, and show how memoisation reduces the time from exponential to linear. (10 marks)
  2. Find the LCS of PATNA and PUNE by filling the table, and state the time complexity. (10 marks)
  3. Find the optimal bracketing for matrices of sizes 10×2010 \times 20, 20×520 \times 5, 5×305 \times 30 and 30×1030 \times 10 using dynamic programming. (15 marks)

Answer plan for question 3.

  • Write the dimension list p=10,20,5,30,10p = 10, 20, 5, 30, 10 and state that m[i][j]m[i][j] is the least cost of multiplying matrices ii to jj.
  • State the recurrence m[i][j]=min⁡i≤k<j(m[i][k]+m[k+1][j]+pi−1⋅pk⋅pj)m[i][j] = \min_{i \le k < j} (m[i][k] + m[k + 1][j] + p_{i-1} \cdot p_k \cdot p_j), with m[i][i]=0m[i][i] = 0.
  • Fill chains of length 2 to get m[1][2]=1,000m[1][2] = 1{,}000, m[2][3]=3,000m[2][3] = 3{,}000 and m[3][4]=1,500m[3][4] = 1{,}500.
  • Fill chains of length 3 to get m[1][3]=2,500m[1][3] = 2{,}500 and m[2][4]=2,500m[2][4] = 2{,}500, recording the best split points.
  • Compute m[1][4]=min⁡(m[2][4]+2,000,m[1][2]+m[3][4]+500,m[1][3]+3,000)=min⁡(4,500,3,000,5,500)=3,000m[1][4] = \min(m[2][4] + 2{,}000, m[1][2] + m[3][4] + 500, m[1][3] + 3{,}000) = \min(4{,}500, 3{,}000, 5{,}500) = 3{,}000.
  • Conclude that the optimal order is (A1A2)(A3A4)(A_1A_2)(A_3A_4), and state that the method takes Θ(n3)\Theta(n^3) time and Θ(n2)\Theta(n^2) 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 φn\varphi^n, while DP makes it Θ(n)\Theta(n) time with Θ(1)\Theta(1) extra space.
  • The running time of a DP is the number of subproblems times the work per subproblem.
  • 0/1 knapsack uses K[i][w]=max⁡(K[i−1][w],vi+K[i−1][w−wi])K[i][w] = \max(K[i - 1][w], v_i + K[i - 1][w - w_i]) and takes Θ(nW)\Theta(nW), which is pseudo-polynomial.
  • LCS uses a match on the diagonal plus one, otherwise the larger of up and left, and takes Θ(mn)\Theta(mn).
  • Edit distance takes the minimum of delete, insert and substitute, and GATE to GREAT is 3.
  • Matrix chain uses m[i][j]=min⁡i≤k<j(m[i][k]+m[k+1][j]+pi−1⋅pk⋅pj)m[i][j] = \min_{i \le k < j} (m[i][k] + m[k + 1][j] + p_{i-1} \cdot p_k \cdot p_j) and takes Θ(n3)\Theta(n^3).
  • 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 Θ(V3)\Theta(V^3).

Check yourself

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

  1. Dynamic programming is useful when a problem has optimal substructure and:

  2. Which method splits a problem into independent subproblems and does not reuse answers?

  3. Which statement about memoisation and tabulation is TRUE?

  4. How many calls in total does the plain recursive Fibonacci make to compute F(5)F(5), with F(0)F(0) and F(1)F(1) as base cases?

  5. Bottom-up Fibonacci that keeps only the last two values runs in:

  6. Capacity W=5W = 5; items (weight, value): (2, 3), (3, 4), (4, 5), (5, 6). The best 0/1 knapsack value is:

  7. The Θ(nW)\Theta(nW) dynamic program for 0/1 knapsack is called pseudo-polynomial because:

  8. The length of the longest common subsequence of GATE and GREAT is:

  9. The LCS of two strings of lengths mm and nn is found by dynamic programming in:

  10. The edit distance (insert, delete, substitute, each of cost 1) from GATE to GREAT is:

  11. Matrices A (10×20)(10 \times 20), B (20×5)(20 \times 5) and C (5×30)(5 \times 30). The cost of (AB)C in scalar multiplications is:

  12. For matrix dimensions p=10,20,5,30,10p = 10, 20, 5, 30, 10, the minimum number of scalar multiplications is:

  13. The number of ways to fully parenthesise a product of 4 matrices is:

  14. With coins {1, 3, 4}, the minimum number of coins needed to make 6 is:

  15. A dynamic program has Θ(n2)\Theta(n^2) subproblems and each takes Θ(n)\Theta(n) work. Its running time is:

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

What is the difference between memoisation and tabulation?

Memoisation is top-down recursion that stores answers as they are found. Tabulation is bottom-up and fills a table in an order where every needed entry is ready.

What is the LCS recurrence?

If the last characters match, L[i][j] = L[i − 1][j − 1] + 1; otherwise L[i][j] = max(L[i − 1][j], L[i][j − 1]).

Why is the knapsack DP called pseudo-polynomial?

Its Θ(nW) time grows with the value W, but W needs only about log₂ W bits to write, so the time is exponential in the input size.

When should dynamic programming be used instead of greedy?

When the locally best choice can be wrong, as in 0/1 knapsack or coin change with coins {1, 3, 4}, and the subproblems repeat.

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): dynamic programming
  3. NPTEL Programming, Data Structures and Algorithms (CMI, 106106145): memoization, dynamic programming, LCS, edit distance, matrix multiplication