1. Gyanastra
  2. Algorithms
  3. Dynamic Programming Problem Set: LIS, Edit Distance, Coin Change, Rod Cutting and Counting Strings
  4. Edit Distance (Levenshtein Distance)
Free lesson, no account needed 12 min read
Asked in past papers1 time
  • GATE CSE2008

Algorithms · Dynamic Programming Problem Set: LIS, Edit Distance, Coin Change, Rod Cutting and Counting Strings

Edit Distance (Levenshtein Distance)

Allowed operations: insert, delete, replace, each cost 1.

State: dp[i][j]dp[i][j] = min operations to convert X[1..i]X[1..i] into Y[1..j]Y[1..j].

Recurrence: dp[i][j]={ij=0ji=0dp[i−1][j−1]X[i]=Y[j]1+min⁡(dp[i−1][j], dp[i][j−1], dp[i−1][j−1])X[i]≠Y[j]dp[i][j]=\begin{cases} i & j=0\\ j & i=0\\ dp[i-1][j-1] & X[i]=Y[j]\\ 1+\min\big(dp[i-1][j],\ dp[i][j-1],\ dp[i-1][j-1]\big) & X[i]\ne Y[j]\end{cases}

Symbols: dp[i−1][j]dp[i-1][j] = delete X[i]X[i]; dp[i][j−1]dp[i][j-1] = insert Y[j]Y[j]; dp[i−1][j−1]dp[i-1][j-1] = replace.

Answer: dp[m][n]dp[m][n]. Time/space O(mn)O(mn); length only can be done in O(min⁡(m,n))O(\min(m,n)) space with two rows.

3.1 Full table: X=X= "kitten", Y=Y= "sitting" (m=6m=6, n=7n=7)

Base row/column: dp[i][0]=idp[i][0]=i, dp[0][j]=jdp[0][j]=j.

εsitting
ε01234567
k11234567
i22123456
t33212345
t44321234
e55432234
n66543323

Let me verify a few cells by hand:

  • dp[1][1]dp[1][1]: k vs s differ → 1+min⁡(dp[0][1]=1, dp[1][0]=1, dp[0][0]=0)=11+\min(dp[0][1]=1,\ dp[1][0]=1,\ dp[0][0]=0)=1. ✔
  • dp[2][2]dp[2][2]: i vs i equal → dp[1][1]=1dp[1][1]=1. ✔
  • dp[3][3]dp[3][3]: t vs t equal → dp[2][2]=1dp[2][2]=1. ✔
  • dp[6][7]dp[6][7]: n vs g differ → 1+min⁡(dp[5][7]=4, dp[6][6]=2, dp[5][6]=3)=1+2=31+\min(dp[5][7]=4,\ dp[6][6]=2,\ dp[5][6]=3)=1+2=3. ✔

Answer = 3. (kitten → sitten → sittin → sitting.)

3.2 Relation to LCS

dpedit(m,n)=m+n−2⋅LCS(X,Y)(insert+delete only, no replace)dp_{\text{edit}}(m,n) = m + n - 2\cdot \text{LCS}(X,Y) \quad\text{(insert+delete only, no replace)}

With replace allowed, the relation is not a simple closed form; the standard identity m+n−2 LCSm+n-2\,\text{LCS} holds for the insert/delete-only variant. GATE sometimes asks the insert/delete-only version — read the operation list carefully.

Shortest Common Supersequence (SCS): ∣SCS∣=m+n−LCS(X,Y).|\text{SCS}| = m + n - \text{LCS}(X,Y).

Longest Palindromic Subsequence (LPS): LPS(s)=LCS(s, reverse(s)).\text{LPS}(s) = \text{LCS}(s,\ \text{reverse}(s)).

Example: s=s= "character" (c h a r a c t e r). The longest palindromic subsequence is "carac" (positions 1, 3, 4, 5, 6), so LPS=LCS(s,reverse(s))=5\text{LPS}=\text{LCS}(s,\text{reverse}(s))=5.

3.3 LCS table recap (one exact example)

X=X= "ABCBDAB" (m=7m=7), Y=Y= "BDCABA" (n=6n=6). Recurrence: dp[i][j]=dp[i−1][j−1]+1dp[i][j]=dp[i-1][j-1]+1 if X[i]=Y[j]X[i]=Y[j], else max⁡(dp[i−1][j],dp[i][j−1])\max(dp[i-1][j],dp[i][j-1]).

εBDCABA
ε0000000
A0000111
B0111122
C0112222
B0112233
D0122233
A0122334
B0122344

Spot checks: dp[2][5]dp[2][5] (B vs B): equal → dp[1][4]+1=1+1=2dp[1][4]+1=1+1=2 ✔. dp[7][6]dp[7][6] (B vs A): max⁡(dp[6][6]=3, dp[7][5]=4)=4\max(dp[6][6]=3,\ dp[7][5]=4)=4 ✔.

LCS length = 4 (e.g. "BCBA"). Time/space O(mn)O(mn); length only in O(min⁡(m,n))O(\min(m,n)) space.


Coin Change

Two different problems — never mix their recurrences.

4.1 Minimum number of coins (unlimited supply)

State: dp[a]dp[a] = min coins to make amount aa.

Recurrence: dp[0]=0,dp[a]=min⁡ci≤a(dp[a−ci]+1),dp[a]=∞ if impossible.dp[0]=0,\qquad dp[a]=\min_{c_i\le a}\big(dp[a-c_i]+1\big),\quad dp[a]=\infty \text{ if impossible.}

Answer: dp[A]dp[A]. Time O(A⋅k)O(A\cdot k) where kk = number of denominations.

Example: coins {1,3,4}\{1,3,4\}, A=6A=6.

aa0123456
dp[a]dp[a]0121122

Check dp[6]dp[6]: min⁡(dp[5]+1=3, dp[3]+1=2, dp[2]+1=3)=2\min(dp[5]+1=3,\ dp[3]+1=2,\ dp[2]+1=3)=2 (coins 3+3). ✔ Note greedy (4+1+1=3) is not optimal — this is the classic greedy-fails example.

4.2 Number of ways (unlimited supply, order does not matter)

State: dp[a]dp[a] = number of combinations summing to aa.

Recurrence (iterate coins outer, amounts inner): dp[0]=1,dp[a]+=dp[a−ci]  for each coin ci and a≥ci.dp[0]=1,\qquad dp[a]\mathrel{+}= dp[a-c_i]\ \text{ for each coin } c_i \text{ and } a\ge c_i.

Example: coins {1,2,3}\{1,2,3\}, A=4A=4.

Coin processeddp[0]dp[0]dp[1]dp[1]dp[2]dp[2]dp[3]dp[3]dp[4]dp[4]
init10000
c=111111
c=211223
c=311234

Answer = 4 (1+1+1+1, 1+1+2, 2+2, 1+3). ✔

Order matters (permutations)? Swap loops: amounts outer, coins inner — then dp[4]dp[4] counts ordered sequences. For {1,2,3}\{1,2,3\}, A=4A=4: dp[0]=1dp[0]=1, dp[1]=1dp[1]=1, dp[2]=dp[1]+dp[0]=2dp[2]=dp[1]+dp[0]=2, dp[3]=dp[2]+dp[1]+dp[0]=4dp[3]=dp[2]+dp[1]+dp[0]=4, dp[4]=dp[3]+dp[2]+dp[1]=7dp[4]=dp[3]+dp[2]+dp[1]=7. (Sequences: 1111,112,121,13,211,22,31 = 7.) ✔

4.3 0/1 coin change (each coin used at most once)

State: dp[i][a]dp[i][a] = ways using first ii coins to make aa. dp[i][a]=dp[i−1][a]+dp[i−1][a−ci].dp[i][a]=dp[i-1][a]+dp[i-1][a-c_i]. Iterate aa downward in 1-D to avoid reuse. This is exactly subset-sum counting.


Rod Cutting

State: r[n]r[n] = max revenue from a rod of length nn; prices p[1..n]p[1..n].

Recurrence: r[0]=0,r[n]=max⁡1≤i≤n(p[i]+r[n−i]).r[0]=0,\qquad r[n]=\max_{1\le i\le n}\big(p[i]+r[n-i]\big).

Answer: r[n]r[n]. Time O(n2)O(n^2), space O(n)O(n).

Example: p=[1,5,8,9,10,17,17,20]p=[1,5,8,9,10,17,17,20] for lengths 1..8.

nn12345678
r[n]r[n]1581013171822

Check r[4]r[4]: max⁡(p1+r3=1+8=9, p2+r2=5+5=10, p3+r1=8+1=9, p4+r0=9)=10\max(p1+r3=1+8=9,\ p2+r2=5+5=10,\ p3+r1=8+1=9,\ p4+r0=9)=10 ✔ (2+2). Check r[5]r[5]: max⁡(1+10=11, 5+8=13, 8+5=13, 9+1=10, 10)=13\max(1+10=11,\ 5+8=13,\ 8+5=13,\ 9+1=10,\ 10)=13 ✔ (2+3). Check r[8]r[8]: max⁡(1+18=19, 5+17=22, 8+13=21, 9+10=19, 10+8=18, 17+5=22, 17+1=18, 20)=22\max(1+18=19,\ 5+17=22,\ 8+13=21,\ 9+10=19,\ 10+8=18,\ 17+5=22,\ 17+1=18,\ 20)=22 ✔ (2+6 or 6+2).


0/1 Knapsack Recap (pseudo-polynomial)

State: dp[i][w]dp[i][w] = max value using first ii items with capacity ww.

Recurrence: dp[i][w]={dp[i−1][w]wi>wmax⁡(dp[i−1][w], vi+dp[i−1][w−wi])wi≤wdp[i][w]=\begin{cases}dp[i-1][w] & w_i>w\\ \max\big(dp[i-1][w],\ v_i+dp[i-1][w-w_i]\big) & w_i\le w\end{cases}

Answer: dp[n][W]dp[n][W]. Time O(nW)O(nW) — pseudo-polynomial because WW is a value, not input length; the input size is log⁡W\log W bits, so the algorithm is exponential in input size. This is why 0/1 knapsack is NP-hard yet has this DP.

Example: items (w,v)(w,v): (1,1),(3,4),(4,5),(5,7), W=7W=7.

i\wi\backslash w01234567
000000000
1 (1,1)01111111
2 (3,4)01145555
3 (4,5)01145669
4 (5,7)01145789

Check dp[3][7]dp[3][7]: max⁡(dp[2][7]=5, 5+dp[2][3]=5+4=9)=9\max(dp[2][7]=5,\ 5+dp[2][3]=5+4=9)=9 ✔. dp[4][7]dp[4][7]: max⁡(9, 7+dp[3][2]=7+1=8)=9\max(9,\ 7+dp[3][2]=7+1=8)=9 ✔. Answer 9.


Subset Sum and Partition

Subset sum: does some subset of {a1..an}\{a_1..a_n\} sum to TT? dp[i][t]=dp[i−1][t] ∨ dp[i−1][t−ai].dp[i][t]=dp[i-1][t]\ \lor\ dp[i-1][t-a_i]. Boolean table, O(nT)O(nT) time, O(T)O(T) space (iterate tt downward).

Partition: can the array be split into two equal-sum halves? Answer yes iff total sum SS is even and subset-sum with T=S/2T=S/2 is true.

Example: [1,5,11,5][1,5,11,5], S=22S=22, T=11T=11. Subset {11}\{11\} or {1,5,5}\{1,5,5\} → yes. ✔ Example: [1,2,3,5][1,2,3,5], S=11S=11 odd → no. ✔


8.1 Binary strings of length nn with no two consecutive 0s

Let xnx_n = count. x1=2x_1=2 (0,1), x2=3x_2=3 (01,10,11). Recurrence xn=xn−1+xn−2x_n=x_{n-1}+x_{n-2} (Fibonacci).

nn123456
xnx_n23581321

x5=13x_5=13 ✔. Time O(n)O(n), space O(1)O(1) with two variables.

8.2 Climbing nn stairs (1 or 2 steps at a time)

f(0)=1, f(1)=1, f(n)=f(n−1)+f(n−2)f(0)=1,\ f(1)=1,\ f(n)=f(n-1)+f(n-2).

nn012345
f(n)f(n)112358

f(5)=8f(5)=8 ✔. (If 1,2,3 steps allowed: f(n)=f(n−1)+f(n−2)+f(n−3)f(n)=f(n-1)+f(n-2)+f(n-3), tribonacci.)

8.3 Number of paths in an m×nm\times n grid (right/down only)

dp[i][j]=dp[i−1][j]+dp[i][j−1],dp[0][j]=dp[i][0]=1.dp[i][j]=dp[i-1][j]+dp[i][j-1],\quad dp[0][j]=dp[i][0]=1. Closed form: (m+n−2m−1)\binom{m+n-2}{m-1}. For 3×33\times3 grid (3 rows, 3 cols): (42)=6\binom{4}{2}=6. Table:

012
0111
1123
2136

✔ Answer 6.


Matrix Chain Multiplication (full table)

Dimensions: A1=10×30A_1=10\times30, A2=30×5A_2=30\times5, A3=5×60A_3=5\times60. So p=[10,30,5,60]p=[10,30,5,60], n=3n=3 matrices.

State: m[i][j]m[i][j] = min scalar multiplications to compute Ai⋯AjA_i\cdots A_j.

Recurrence: m[i][i]=0,m[i][j]=min⁡i≤k<j(m[i][k]+m[k+1][j]+pi−1 pk pj).m[i][i]=0,\qquad m[i][j]=\min_{i\le k<j}\big(m[i][k]+m[k+1][j]+p_{i-1}\,p_k\,p_j\big).

Answer: m[1][n]m[1][n]. Subproblems: O(n2)O(n^2); time: O(n3)O(n^3); number of parenthesizations: Catalan Cn−1=1n(2n−2n−1)C_{n-1}=\frac{1}{n}\binom{2n-2}{n-1}.

Fill by chain length:

Chain lengthCellComputationValue
1m[1][1],m[2][2],m[3][3]m[1][1],m[2][2],m[3][3]base0
2m[1][2]m[1][2]k=1k=1: 0+0+p0p1p2=10⋅30⋅5=15000+0+p_0p_1p_2=10\cdot30\cdot5=15001500
2m[2][3]m[2][3]k=2k=2: 0+0+p1p2p3=30⋅5⋅60=90000+0+p_1p_2p_3=30\cdot5\cdot60=90009000
3m[1][3]m[1][3]k=1k=1: m[1][1]+m[2][3]+p0p1p3=0+9000+10⋅30⋅60=9000+18000=27000m[1][1]+m[2][3]+p_0p_1p_3=0+9000+10\cdot30\cdot60=9000+18000=27000
k=2k=2: m[1][2]+m[3][3]+p0p2p3=1500+0+10⋅5⋅60=1500+3000=4500m[1][2]+m[3][3]+p_0p_2p_3=1500+0+10\cdot5\cdot60=1500+3000=45004500

Optimal cost = 4500, split at k=2k=2: (A1A2)A3(A_1A_2)A_3. Check: A1A2A_1A_2 costs 10⋅30⋅5=150010\cdot30\cdot5=1500 giving 10×510\times5; then ×A3\times A_3 costs 10⋅5⋅60=300010\cdot5\cdot60=3000; total 45004500. ✔

Catalan for n=3n=3: C2=13(42)=63=2C_2=\frac{1}{3}\binom{4}{2}=\frac{6}{3}=2 parenthesizations: (A1(A2A3))(A_1(A_2A_3)) and ((A1A2)A3)((A_1A_2)A_3). ✔


Optimal Binary Search Tree (idea only)

State: cost[i][j]cost[i][j] = min expected search cost for keys i..ji..j. cost[i][j]=min⁡i≤r≤j(cost[i][r−1]+cost[r+1][j])+∑k=ijpk.cost[i][j]=\min_{i\le r\le j}\big(cost[i][r-1]+cost[r+1][j]\big)+\sum_{k=i}^{j}p_k. The added term is the sum of probabilities in the range (every node in the subtree gains one comparison). Time O(n3)O(n^3), space O(n2)O(n^2). The optimal root is not necessarily the highest-probability key — a common trap.


Memoisation vs Tabulation

AspectTop-down (memoisation)Bottom-up (tabulation)
DirectionRecursion + cacheIterative fill
ComputesOnly needed statesAll states
StackO(depth)O(\text{depth}) recursion stackNone
OverheadFunction-call overheadLower
Space optimisationHardEasy (rolling rows)
RiskStack overflow on deep nnMust get fill order right

Both give the same asymptotic time; memoisation can be faster when few states are reachable.


Problems That Look Like DP but Are Greedy

ProblemGreedy works?Why
Fractional knapsackYes (value/weight ratio)Fractional — exchange argument
Activity selectionYes (earliest finish)Exchange argument
Huffman codingYesExchange argument (two least frequent are siblings at the deepest level)
Dijkstra (non-negative weights)YesGreedy + relaxation
0/1 knapsackNoNeeds DP
Coin change (min coins)No in general (e.g. {1,3,4}\{1,3,4\}, A=6A=6)Greedy gives 3, optimal 2
LISNo simple greedyNeeds DP / patience
Rod cuttingNoNeeds DP

Pages 1–2 of 2