Skip to main content

Algorithms

Dynamic Programming

DP questions ask for a recurrence, a table value, or a time/space bound. Learn the standard recurrences (knapsack, LCS, matrix chain, rod cutting, coin change) and practise filling small tables quickly.

~5 hrs ~1.5–2 marks · Must-score 10 samples · 10 practice · 10 cards

GATE CSE dynamic programming — overlapping subproblems, optimal substructure, memoization vs tabulation, 0/1 knapsack, LCS, LIS, edit distance, matrix-chain multiplication, rod cutting and coin change recurrences.

Learning outcomes

  • Explain overlapping subproblems and optimal substructure and contrast DP with D&C and greedy
  • Write and fill the tables for 0/1 knapsack, LCS, edit distance, coin change and rod cutting
  • Apply the matrix-chain recurrence and compute the minimum number of scalar multiplications
  • State time and space bounds of standard DP algorithms and distinguish memoization from tabulation

DP paradigm: overlapping subproblems and optimal substructure

  • Dynamic programming solves a problem by combining solutions of SUBPROBLEMS and storing each result so it is computed only once.
  • Optimal substructure: an optimal solution of the problem contains optimal solutions of its subproblems. Overlapping subproblems: the same subproblems are needed again and again, so recursion without storage is exponential.
  • Memoization (top-down): recursive algorithm plus a lookup table; computes only the subproblems actually needed. Tabulation (bottom-up): fill the table iteratively in dependency order; no recursion overhead and allows space optimisation.
  • Time = (number of distinct subproblems) × (work per subproblem). Space = size of the table (often reducible to one or two rows).
  • Naive Fibonacci F(n) = F(n−1) + F(n−2) makes Θ(φ^n) calls; with memoization or a table it takes Θ(n) time, and Θ(1) space with two variables.
  • D&C: independent subproblems. Greedy: one choice, no table. DP: tries all choices via stored optimal sub-results. Problems like longest SIMPLE path lack optimal substructure and are not solvable by DP.
  • Five-step recipe for any DP problem: (1) define the STATE (what the indices mean), (2) write the recurrence, (3) set the base cases, (4) choose the fill order that respects dependencies, (5) locate the answer (corner cell, or the best value over a row).
  • Memoisation turns exponential recursion into (number of states) × (work per state). Naive Fibonacci makes 2F(n+1) − 1 calls; the memoised version evaluates only n + 1 distinct values.
  • Space optimisation: when row i depends only on row i − 1 (knapsack, LCS) two rows or one row suffice, but the solution path can then no longer be traced back without extra information.
  • Top-down may evaluate fewer states when many are unreachable, but pays recursion overhead and can overflow the call stack for depth around 10^5; bottom-up avoids both.
TechniqueSubproblemsStores results?Example
Divide & ConquerIndependentNoMerge sort
Dynamic ProgrammingOverlappingYesLCS, knapsack
GreedySingle choice per stepNoHuffman, Kruskal
Plain recursionOverlapping (wasteful)NoNaive Fibonacci

Worked example

Problem. How many distinct subproblems does memoized Fibonacci solve for F(n), and what is the time?

Solution. F(0) … F(n) = n + 1 subproblems, each with O(1) work, so Θ(n) time.

0/1 knapsack, subset sum and coin change

  • 0/1 knapsack with items (w_i, v_i) and capacity W: let K[i][w] be the best value using the first i items with capacity w. K[i][w] = K[i−1][w] if w_i > w, else max(K[i−1][w], v_i + K[i−1][w − w_i]). K[0][w] = K[i][0] = 0.
  • Time Θ(nW) and space Θ(nW), reducible to Θ(W) by iterating w downwards in a single array. It is PSEUDO-polynomial because W is a number, not its bit length.
  • Subset sum: S[i][s] = true if some subset of the first i numbers sums to s: S[i][s] = S[i−1][s] OR S[i−1][s − a_i]. Time Θ(n·target).
  • Coin change (minimum coins): C[x] = 1 + min over coins c ≤ x of C[x − c], C[0] = 0. Number of ways (combinations): ways[x] += ways[x − c] for each coin c in the OUTER loop, giving Θ(n·amount).
  • Greedy fails for arbitrary coin systems (e.g., {1, 3, 4} for 6), so DP is required.
  • Space-optimised 0/1 knapsack uses ONE array and iterates w from W DOWN to w_i so each item is used at most once. Iterating w upwards lets an item be reused, which solves the UNBOUNDED knapsack instead.
  • Unbounded knapsack: K[w] = max over items of (v_i + K[w − w_i]), time Θ(nW). Rod cutting and coin change are unbounded problems; 0/1 knapsack and subset sum are not.
  • Recovering the chosen items: start at K[n][W]; if K[i][w] ≠ K[i−1][w] then item i was taken, so set w = w − w_i; then move to row i − 1. Repeat down to row 0.
  • The table has (n + 1)(W + 1) cells and each cell costs O(1), giving Θ(nW). If W is written with m bits then W ≈ 2^m and the time is exponential in the input size, hence PSEUDO-polynomial.
  • Counting combinations versus permutations: with coins in the OUTER loop you count combinations (coins {1, 2, 3}, amount 4 gives 4); with amounts in the outer loop you count ordered sequences (gives 7).

Formulas to remember

  • K[i][w] = max(K[i−1][w], v_i + K[i−1][w − w_i])
  • C[x] = 1 + min_c C[x − c], C[0] = 0
  • Time Θ(nW), Space Θ(W) optimised

Worked example

Problem. Capacity 5; items (weight, value): (2,3), (3,4), (4,5), (5,6). Find the best value.

Solution. Options within weight 5: {2,3} = 3 + 4 = 7; {5} = 6; {4} = 5. The maximum is 7.

Filled 0/1 knapsack DP table for three items and capacity 5 with the traceback cells highlighted and optimum 7
0/1 knapsack table for items (2,3), (3,4), (4,5) with W = 5; the optimum 7 is traced back to items 1 and 2.

LCS, LIS and edit distance

  • LCS of X[1..m] and Y[1..n]: L[i][j] = L[i−1][j−1] + 1 if X[i] = Y[j], else max(L[i−1][j], L[i][j−1]); L[0][j] = L[i][0] = 0. Time and space Θ(mn); space reducible to Θ(min(m, n)) if only the length is needed.
  • A subsequence need not be contiguous (substring/longest common substring is different). The number of subsequences of a string of length n is 2^n, so brute force is exponential.
  • LIS (longest increasing subsequence): L[i] = 1 + max L[j] over j < i with a[j] < a[i], giving Θ(n²); with binary search on tails the time is Θ(n log n). LIS equals the LCS of the array and its sorted version (distinct values).
  • Edit distance (Levenshtein): D[i][j] = D[i−1][j−1] if X[i] = Y[j], else 1 + min(D[i−1][j] (delete), D[i][j−1] (insert), D[i−1][j−1] (replace)). Θ(mn).
  • Table-filling order matters: each cell depends on the cell above, to the left, and diagonally up-left, so fill row by row.
  • Reading the LCS: start at L[m][n]; on a match record the character and move diagonally, otherwise move to the larger of the up and left neighbours. Reverse the recorded characters. Ties give different (equally long) LCSs.
  • Longest common SUBSTRING uses S[i][j] = S[i−1][j−1] + 1 on a match and 0 otherwise; the answer is the MAXIMUM cell in the table, not the corner cell.
  • Useful identities: LCS ≤ min(m, n); LCS(X, X) = n; shortest common supersequence length = m + n − LCS; edit distance with only insert and delete = m + n − 2·LCS.
  • Edit distance examples: kitten → sitting = 3 (substitute k→s, substitute e→i, insert g); SUNDAY → SATURDAY = 3. Edit distance is symmetric and satisfies the triangle inequality.

Formulas to remember

  • L[i][j] = L[i−1][j−1] + 1 if X[i] = Y[j]
  • L[i][j] = max(L[i−1][j], L[i][j−1]) otherwise

Worked example

Problem. Find the LCS length of X = ABCBDAB and Y = BDCABA.

Solution. One LCS is BCBA (also BDAB, BCAB). Filling the 7 × 6 table gives L[7][6] = 4.

LCS dynamic programming table for ABCBDAB and BDCABA with the traceback path highlighted and LCS length 4
LCS table for X = ABCBDAB and Y = BDCABA; the highlighted traceback reads BCBA.

Matrix-chain multiplication and rod cutting

  • Matrix chain: matrices A1 … An where Ai has dimensions p[i−1] × p[i]. Let M[i][j] be the minimum scalar multiplications for Ai … Aj. M[i][i] = 0 and M[i][j] = min over i ≤ k < j of M[i][k] + M[k+1][j] + p[i−1]·p[k]·p[j].
  • Number of subproblems = n(n+1)/2 = Θ(n²), each tries O(n) split points: time Θ(n³), space Θ(n²). The number of possible parenthesisations is the Catalan number C(n−1), exponential.
  • Multiplying a p × q matrix by a q × r matrix costs p·q·r scalar multiplications. The ORDER of multiplication changes cost but not the result.
  • Rod cutting: prices p_i for length i. R[n] = max over 1 ≤ i ≤ n of p_i + R[n − i], R[0] = 0. Time Θ(n²), space Θ(n).
  • Optimal BST and Floyd–Warshall are other tabulation problems; Floyd–Warshall is Θ(V³) time, Θ(V²) space.
  • Fill order for matrix chain is by CHAIN LENGTH l = 2, 3, …, n (diagonal by diagonal in the upper triangle), because M[i][j] needs the shorter chains inside it.
  • Store the best split s[i][j] = k that achieves each minimum; the optimal parenthesisation is recovered recursively from s[1][n].
  • Number of ways to parenthesise n matrices is the Catalan number C(n−1): n = 4 gives 5, n = 5 gives 14, so brute force is exponential.
  • Index trap: n matrices need a dimension array p of n + 1 entries, and matrix Ai is p[i−1] × p[i]. Confusing p-indices with matrix indices is the most common slip in GATE numerical questions.
  • Rod cutting is an unbounded knapsack with item weights 1, 2, …, n, values p_i and capacity n; this explains its Θ(n²) time and Θ(n) space.

Formulas to remember

  • M[i][j] = min_{i≤k<j} ( M[i][k] + M[k+1][j] + p[i−1] p[k] p[j] )
  • R[n] = max_{1≤i≤n} ( p[i] + R[n−i] )
ProblemTimeSpace (table)Subproblems
0/1 knapsackΘ(nW)Θ(nW) → Θ(W)n × W
LCSΘ(mn)Θ(mn) → Θ(min(m, n))m × n
Matrix chainΘ(n³)Θ(n²)n(n+1)/2
Rod cuttingΘ(n²)Θ(n)n
Floyd–WarshallΘ(V³)Θ(V²)V² per k

Worked example

Problem. Matrices A (10 × 30), B (30 × 5), C (5 × 60). Find the minimum scalar multiplications for ABC.

Solution. (AB)C = 10·30·5 + 10·5·60 = 1500 + 3000 = 4500. A(BC) = 30·5·60 + 10·30·60 = 9000 + 18000 = 27000. Minimum = 4500.

Matrix-chain cost table for dimensions 10, 30, 5, 60, 10 and the optimal split tree giving cost 5000
Matrix chain for p = [10, 30, 5, 60, 10]: the optimal order (A1A2)(A3A4) costs 5000 scalar multiplications.

Worked trace — coin change table for {1, 3, 4}

  • Minimum coins C[x] = 1 + min(C[x − 1], C[x − 3], C[x − 4]) over coins not exceeding x, with C[0] = 0.
  • C[1] = 1, C[2] = 2, C[3] = 1 (coin 3), C[4] = 1 (coin 4), C[5] = 1 + min(C[4], C[2], C[1]) = 2, C[6] = 1 + min(C[5], C[3], C[2]) = 2.
  • C[6] = 2 comes from coin 3 and C[3] (so 3 + 3). Greedy (largest first) would give 4 + 1 + 1 = 3 coins, so the table beats greedy.
  • Number of combinations ways[x]: start ways[0] = 1 and process coins one at a time. After coin 1 every ways[x] = 1; after coin 3 ways[3..6] = 2, 2, 2, 3; after coin 4 ways[4..6] = 3, 3, 4.
  • The four combinations of 6 are 4+1+1, 3+3, 3+1+1+1 and 1×6, matching ways[6] = 4.
  • Time Θ(n·amount) for both tables with n coin types; space Θ(amount).
Amount x0123456
Min coins C[x]0121122
Combinations ways[x]1112334

Worked example

Problem. Coins {1, 3, 4}, amount 7. Find the minimum number of coins.

Solution. C[7] = 1 + min(C[6], C[4], C[3]) = 1 + min(2, 1, 1) = 2, namely 3 + 4. Greedy also gives 4 + 3 here, so the earlier amount 6 is the one that exposes greedy failure.

GATE exam tricks — filling tables fast

  • Write the recurrence first, then the base row/column, then fill. Do not recurse on paper for numerical DP questions.
  • For LCS tables, a diagonal arrow +1 happens only when characters match; otherwise copy the larger of the top and left cells.
  • Count subproblems × work per subproblem for complexity: matrix chain = n² × n = n³; knapsack = nW × 1; rod cutting = n × n.
  • Matrix chain: if cost per split is p[i−1]·p[k]·p[j], double-check dimensions; the shared dimension must match between consecutive matrices.
  • Memoization versus tabulation: both have the same asymptotic time, but memoization uses recursion stack and computes only needed states.
  • Naive recursive Fibonacci is exponential; one extra table makes it linear. The number of recursive calls of naive F(n) is 2F(n+1) − 1.
  • Knapsack DP is NOT polynomial in input size (pseudo-polynomial). Questions asking "is knapsack in P via DP?" expect: no, pseudo-polynomial.
  • Counting grid paths with moves right/down on an r × c grid of cells uses C(r + c − 2, r − 1); DP gives the same number by adding the top and left values.
  • Worked example 2 (LIS): for [10, 9, 2, 5, 3, 7, 101, 18] the LIS length is 4, e.g. 2, 3, 7, 18 or 2, 5, 7, 101. The Θ(n²) DP gives L = [1, 1, 1, 2, 2, 3, 4, 4]; the tails method gives Θ(n log n).
  • Worked example 3 (overlap count): the naive recursive LCS of two strings of length n with no common character makes exponentially many calls (at least 2^n), but only (n+1)² distinct (i, j) states exist; memoisation reduces it to Θ(n²).
  • If an option says "DP always beats greedy in time", reject it: greedy is Θ(n log n) or less when it works. DP is chosen for CORRECTNESS where greedy fails.

Worked example

Problem. Number of right/down paths from the top-left to the bottom-right cell of a 4 × 4 grid?

Solution. Each path has 3 rights and 3 downs: C(6, 3) = 20.

Exam tips

  • Recognise the DP pattern: "number of ways", "minimum cost", "longest subsequence" with overlapping choices.
  • Memorise the four core recurrences: knapsack, LCS, matrix chain, rod cutting.
  • Complexity = distinct subproblems × cost per subproblem.
  • In tables, mark the base cases first and fill in dependency order.
  • Greedy fails for 0/1 knapsack and general coin change — DP is the fix.
Exam pattern · 10 questions

GATE sample questions & answers

10 GATE-style MCQs for Dynamic Programming with full explanations. Attempt each question before revealing the answer.

Q1 Overlapping subproblems

The naive recursive implementation of F(n) = F(n−1) + F(n−2) has time complexity:

  • A) Θ(n)
  • B) Θ(n log n)
  • C) Θ(n²)
  • D) Exponential (Θ(φ^n))
Show answer & explanation

Answer: D

The number of calls satisfies C(n) = C(n−1) + C(n−2) + 1, which grows like φ^n. Memoization reduces it to Θ(n).

Q2

For multiplying a chain of n matrices, the number of distinct subproblems M[i][j] (1 ≤ i ≤ j ≤ n) and the overall DP time are:

  • A) n and Θ(n²)
  • B) n(n+1)/2 and Θ(n³)
  • C) n² and Θ(n²)
  • D) 2^n and Θ(n!)
Show answer & explanation

Answer: B

There are n(n+1)/2 pairs (i, j), and each tries up to n − 1 split points, giving Θ(n³) time.

Q3 LCS table

The length of the longest common subsequence of ABCBDAB and BDCABA is:

  • A) 3
  • B) 4
  • C) 5
  • D) 6
Show answer & explanation

Answer: B

BCBA (and BDAB, BCAB) is a common subsequence of length 4, and the DP table gives L = 4.

Q4

The 0/1 knapsack problem with n items and capacity W is solved by DP in:

  • A) Θ(n + W)
  • B) Θ(nW)
  • C) Θ(n log W)
  • D) Θ(2^n)
Show answer & explanation

Answer: B

There are nW table cells, each filled in O(1) time. The bound is pseudo-polynomial.

Q5

Matrices A (10 × 30), B (30 × 5), C (5 × 60) are multiplied. The minimum number of scalar multiplications is:

  • A) 4500
  • B) 10500
  • C) 27000
  • D) 30000
Show answer & explanation

Answer: A

(AB)C costs 10·30·5 + 10·5·60 = 4500; A(BC) costs 30·5·60 + 10·30·60 = 27000. The minimum is 4500.

Q6

A rod of length 4 can be sold in pieces; prices of lengths 1, 2, 3, 4 are 1, 5, 8, 9. The maximum revenue is:

  • A) 9
  • B) 10
  • C) 11
  • D) 12
Show answer & explanation

Answer: B

R[1] = 1, R[2] = 5, R[3] = 8, R[4] = max(9, 1 + 8, 5 + 5, 8 + 1) = 10 (two pieces of length 2).

Q7

The minimum number of coins needed to make 6 using denominations {1, 3, 4} is:

  • A) 2
  • B) 3
  • C) 4
  • D) 6
Show answer & explanation

Answer: A

C[6] = 1 + min(C[5], C[3], C[2]) = 1 + min(2, 1, 2) = 2, i.e., 3 + 3.

Q8

The length of the longest increasing subsequence of 10, 22, 9, 33, 21, 50, 41, 60 is:

  • A) 4
  • B) 5
  • C) 6
  • D) 7
Show answer & explanation

Answer: B

For example 10, 22, 33, 50, 60 (or 10, 22, 33, 41, 60) has length 5, and no increasing subsequence of length 6 exists.

Q9

The minimum edit distance (insert, delete, replace) between "kitten" and "sitting" is:

  • A) 2
  • B) 3
  • C) 4
  • D) 5
Show answer & explanation

Answer: B

kitten → sitten (replace k by s) → sittin (replace e by i) → sitting (insert g): 3 operations.

Q10

Which property distinguishes dynamic programming from divide and conquer?

  • A) Use of recursion
  • B) Overlapping subproblems
  • C) Splitting the input into parts
  • D) Having a base case
Show answer & explanation

Answer: B

DP applies when subproblems overlap, so storing their results avoids recomputation; D&C subproblems are independent.

Topic drill · 10 questions

10 practice questions — Dynamic Programming

Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.

P1

The number of ways to make change for 4 using coins {1, 2, 3} (order does not matter) is:

  • A) 3
  • B) 4
  • C) 5
  • D) 7
Show answer & explanation

Answer: B) 4

The combinations are 1+1+1+1, 1+1+2, 2+2, 1+3: four ways.

P2

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

  • A) 6
  • B) 7
  • C) 8
  • D) 9
Show answer & explanation

Answer: B) 7

Items (2,3) and (3,4) fit exactly with weight 5 and value 7; no other feasible set beats this.

P3

For the set {3, 34, 4, 12, 5, 2} and target 9, does a subset with that sum exist?

  • A) Yes (4 + 5)
  • B) No
  • C) Only if 34 is used
  • D) Cannot be decided
Show answer & explanation

Answer: A) Yes (4 + 5)

4 + 5 = 9, so the subset {4, 5} works (another is {3, 4, 2}). 34 exceeds the target and is never used.

P4

The minimum extra space needed to compute the n-th Fibonacci number bottom-up is:

  • A) Θ(1)
  • B) Θ(log n)
  • C) Θ(n)
  • D) Θ(n²)
Show answer & explanation

Answer: A) Θ(1)

Only the previous two values are needed, so two variables suffice.

P5

The LCS length of AGGTAB and GXTXAYB is:

  • A) 3
  • B) 4
  • C) 5
  • D) 6
Show answer & explanation

Answer: B) 4

The LCS is GTAB, of length 4.

P6

The Floyd–Warshall all-pairs shortest-path algorithm on V vertices runs in:

  • A) Θ(V²)
  • B) Θ(V³)
  • C) Θ(VE)
  • D) Θ(V² log V)
Show answer & explanation

Answer: B) Θ(V³)

Three nested loops over k, i, j each from 1 to V.

P7

Matrices of dimensions 40×20, 20×30, 30×10, 10×30 are multiplied in the best order. The minimum scalar multiplications are:

  • A) 18000
  • B) 26000
  • C) 30000
  • D) 48000
Show answer & explanation

Answer: B) 26000

The optimal parenthesisation is ((A(BC))D) with cost 20·30·10 + 40·20·10 + 40·10·30 = 6000 + 8000 + 12000 = 26000.

P8

Which statement about memoization is correct?

  • A) It is bottom-up and fills the entire table
  • B) It is top-down and computes only the subproblems that are actually needed
  • C) It has worse asymptotic time than tabulation always
  • D) It does not need recursion
Show answer & explanation

Answer: B) It is top-down and computes only the subproblems that are actually needed

Memoization caches the results of a recursive algorithm, so only reachable subproblems are computed.

P9

The rod cutting problem for a rod of length n using DP takes:

  • A) Θ(n)
  • B) Θ(n log n)
  • C) Θ(n²)
  • D) Θ(2^n)
Show answer & explanation

Answer: C) Θ(n²)

R[n] needs a loop of up to n choices for each of n lengths.

P10

The number of paths from the top-left to the bottom-right of a 4 × 4 grid of cells with only right and down moves is:

  • A) 8
  • B) 16
  • C) 20
  • D) 70
Show answer & explanation

Answer: C) 20

Each path has 3 rights and 3 downs in some order: C(6, 3) = 20.

Topic FAQs

What is the difference between memoization and tabulation?

Memoization is top-down recursion with caching of results; tabulation is bottom-up iteration over a table. Both give the same asymptotic time.

Why is knapsack DP called pseudo-polynomial?

Its Θ(nW) time is polynomial in the numeric value W, but exponential in the number of bits needed to write W.

How is DP different from divide and conquer?

D&C subproblems are independent; DP subproblems overlap, so results are stored and reused.

Is the longest common subsequence the same as the longest common substring?

No. A subsequence need not be contiguous; a substring must be contiguous, and the two use different recurrences.

Quick revision · 10 cards

10 flashcards — Dynamic Programming

Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.

Q1 What are overlapping subproblems and optimal substructure?
Q2 What is the difference between memoization and tabulation?
Q3 What is the recurrence for the 0/1 knapsack table?
Q4 Why is the Θ(nW) knapsack algorithm called pseudo-polynomial?
Q5 What is the LCS recurrence for two strings X and Y?
Q6 What is the time and space complexity of the LCS dynamic programme?
Q7 What is the matrix-chain multiplication recurrence?
Q8 Why does the matrix-chain DP take Θ(n³) time and Θ(n²) space?
Q9 What is the recurrence for rod cutting and its complexity?
Q10 Why does greedy fail for the coin change problem with denominations {1, 3, 4}?