Data Structures & Algorithms chapters (13)
  1. 01Introduction to DSA
  2. 02Arrays & Strings Algorithms
  3. 03Searching & Sorting Algorithms
  4. 04Asymptotic Analysis & Complexity
  5. 05Linked Lists
  6. 06Stacks & Queues
  7. 07Hashing & Hash Tables
  8. 08Recursion & Backtracking
  9. 09Binary Trees & BST
  10. 10Heaps & Priority Queues
  11. 11Graphs & Graph Algorithms
  12. 12Greedy Algorithms & Bit Manipulation
  13. 13Dynamic Programming (DP)

Chapter 13

Dynamic Programming (DP)

4 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Dynamic programming solves problems with optimal substructure and overlapping subproblems by storing results: top-down memoization or bottom-up tabulation.

It converts exponential recursion into polynomial time.

DP is the hardest recurring interview topic; the three classic problems here are templates for dozens of others.

Resource allocation, diff tools (LCS), spell correction (edit distance), sequence alignment in bioinformatics, route optimization.

1

Memoization (Top-Down) vs Tabulation (Bottom-Up)

Memoization (top-down) caches results of a recursive function keyed by its arguments so each subproblem is computed once. Tabulation (bottom-up) fills a table iteratively from the base cases in dependency order. Both give time = (number of states) x (cost per transition).

In short: Remember answers you already computed instead of recomputing them: lazily with recursion, or eagerly with a table.

DP: store answers to overlapping subproblems

Think about it

Every DP solution is state + transition; knowing both implementation styles and their trade-offs is expected in interviews.

Requirements

overlapping subproblems (naive recursion repeats work) and optimal substructure.

Steps

  • 1define state (what parameters uniquely describe a subproblem),
  • 2recurrence,
  • 3base cases,
  • 4iteration order so dependencies are ready,
  • 5answer cell.

Fibonacci: naive O(2^n); memo/table O(n) time; rolling two variables O(1) space.

Memoization computes only reachable states and is easier to write but pays recursion overhead and stack depth (RecursionError for deep n in Python); tabulation avoids recursion and enables space optimization (keep only the previous row/column).

Climbing stairs, house robber (dp[i] = max(dp[i-1], dp[i-2] + a[i])), coin change (min coins: dp[x] = min(dp[x-c]+1); number of ways: loop coins outer for combinations, amount outer for permutations), unique paths and min path sum are 1-D/2-D table examples.

Greedy vs DP: greedy needs the greedy-choice property; when it fails (coins 1,3,4 for amount 6: greedy 4+1+1 = 3 coins, optimal 3+3 = 2) use DP.

States must not carry unneeded parameters (state explosion).

Time = states x transitions; space = states (reducible).

Reconstruction: store parent choices or backtrack through the table.

Bitmask DP handles subsets (TSP O(n^2 2^n)).

Key points

  • Optimal substructure: Optimal solution built from optimal solutions of subproblems.
  • Overlapping subproblems: Same subproblem arises repeatedly in the recursion tree.
  • State: Parameters that uniquely identify a subproblem.
  • Rolling array: Keep only the rows needed to cut space.

Example

Code
Memo, table, coin change:
from functools import lru_cache

def fib_memo(n):                       # top-down
    @lru_cache(None)
    def f(i): return i if i < 2 else f(i - 1) + f(i - 2)
    return f(n)

def fib_tab(n):                        # bottom-up, O(1) space
    a, b = 0, 1
    for _ in range(n): a, b = b, a + b
    return a

def coin_change_min(coins, amount):    # O(amount * len(coins))
    INF = float('inf')
    dp = [0] + [INF] * amount
    for x in range(1, amount + 1):
        for c in coins:
            if c <= x and dp[x - c] + 1 < dp[x]:
                dp[x] = dp[x - c] + 1
    return dp[amount] if dp[amount] != INF else -1

def coin_ways(coins, amount):          # combinations: coins OUTER
    dp = [1] + [0] * amount
    for c in coins:
        for x in range(c, amount + 1):
            dp[x] += dp[x - c]
    return dp[amount]

def house_robber(a):
    prev = cur = 0
    for x in a: prev, cur = cur, max(cur, prev + x)
    return cur
2

0/1 Knapsack Problem

Given n items with weight w[i] and value v[i] and capacity W, choose a subset (each item at most once) maximizing total value with total weight <= W. Recurrence: dp[i][c] = max(dp[i-1][c], v[i] + dp[i-1][c - w[i]]) if w[i] <= c, else dp[i-1][c]. Time O(nW), space O(nW) (O(W) optimized).

In short: For each item decide take or skip, remembering the best value for every capacity.

0/1 Knapsack: take or skip each item

Think about it

The archetype for selection-with-budget DP; the reverse-loop trick and pseudo-polynomial nature are classic questions.

dp[i][c] = best value using the first i items with capacity c; base dp[0][c] = 0; answer dp[n][W].

Space optimization: use a 1-D array and iterate capacity from W DOWN to w[i], so that dp[c - w[i]] still holds the previous item row (iterating upward would allow reuse of the same item = UNBOUNDED knapsack, where upward iteration is correct).

Complexity O(nW) is pseudo-polynomial: polynomial in the numeric value of W, exponential in its bit length; 0/1 knapsack is NP-complete.

Greedy by value/weight ratio is optimal only for FRACTIONAL knapsack (sort by ratio, O(n log n)), not 0/1.

Recover chosen items by walking back from dp[n][W]: if dp[i][c] !

= dp[i-1][c] item i was taken.

Variants: subset sum (boolean dp), partition equal subset sum (target = total/2), target sum with +/-, count of subsets with given sum (dp[c] += dp[c - x]), minimum subset difference, rod cutting and unbounded knapsack.

Brute force O(2^n); meet in the middle O(2^(n/2)).

Edge cases: weight 0 items, w[i] > W, W = 0 (answer 0), negative weights invalid.

Key points

  • Pseudo-polynomial: Polynomial in numeric input value, not in input length.
  • Fractional knapsack: Items divisible; greedy by ratio is optimal.
  • Subset sum: Can a subset reach exactly target? Boolean knapsack.

Example

Code
0/1 knapsack, reconstruction, partition:
def knapsack_01(w, v, W):              # O(nW) time, O(W) space
    dp = [0] * (W + 1)
    for wi, vi in zip(w, v):
        for c in range(W, wi - 1, -1):  # DOWNWARD: each item once
            dp[c] = max(dp[c], dp[c - wi] + vi)
    return dp[W]

def knapsack_table(w, v, W):           # 2-D with reconstruction
    n = len(w)
    dp = [[0] * (W + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        for c in range(W + 1):
            dp[i][c] = dp[i - 1][c]
            if w[i - 1] <= c:
                dp[i][c] = max(dp[i][c], dp[i - 1][c - w[i - 1]] + v[i - 1])
    chosen, c = [], W
    for i in range(n, 0, -1):
        if dp[i][c] != dp[i - 1][c]:
            chosen.append(i - 1); c -= w[i - 1]
    return dp[n][W], chosen[::-1]

def can_partition(nums):               # subset sum to total/2
    t = sum(nums)
    if t % 2: return False
    t //= 2; dp = [True] + [False] * t
    for x in nums:
        for c in range(t, x - 1, -1):
            dp[c] = dp[c] or dp[c - x]
    return dp[t]
3

Longest Common Subsequence (LCS)

LCS of strings X (length m) and Y (length n) is the longest sequence appearing in both in the same relative order (not necessarily contiguous). dp[i][j] = dp[i-1][j-1] + 1 if X[i-1] == Y[j-1], else max(dp[i-1][j], dp[i][j-1]). Time and space O(mn).

In short: Compare prefixes: if the last characters match extend the common part, otherwise drop a character from one string.

LCS: match chars or skip one side

Think about it

Template for all 2-D string DPs including edit distance; GATE asks table values and complexity.

Base: dp[0][*] = dp[*][0] = 0; answer dp[m][n].

Reconstruct by tracing back from (m,n): equal chars -> take and move diagonally; else move toward the larger neighbour.

Space optimization to O(min(m,n)) with two rows works for the length only (reconstruction needs the table or Hirschberg divide and conquer, O(mn) time, O(m+n) space).

Subsequence vs substring: longest common SUBSTRING needs contiguity: dp[i][j] = dp[i-1][j-1]+1 if equal else 0, with answer = max over all cells.

Related: edit distance dp[i][j] = dp[i-1][j-1] if equal else 1 + min(insert, delete, replace); shortest common supersequence length = m + n - LCS; minimum deletions/insertions to turn X into Y = (m - LCS) + (n - LCS); longest palindromic subsequence = LCS(s, reverse(s)).

Number of distinct subsequences, interleaving string and regex matching are 2-D string DPs of the same form.

Brute force is O(2^m * n) by enumerating subsequences.

Used in diff, version control and DNA alignment.

Worst-case number of states mn; for strings of length 1000 that is 10^6, fine; 10^5 is too large.

Key points

  • Subsequence: Characters in order but not necessarily adjacent.
  • Substring: Contiguous characters.
  • Edit distance: Minimum insert/delete/replace operations to transform X into Y.

Example

Code
LCS, edit distance, palindromic subsequence:
def lcs(x, y):
    m, n = len(x), len(y)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if x[i - 1] == y[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    # reconstruct
    i, j, out = m, n, []
    while i and j:
        if x[i - 1] == y[j - 1]:
            out.append(x[i - 1]); i -= 1; j -= 1
        elif dp[i - 1][j] >= dp[i][j - 1]:
            i -= 1
        else:
            j -= 1
    return dp[m][n], ''.join(reversed(out))

def edit_distance(a, b):
    m, n = len(a), len(b)
    prev = list(range(n + 1))
    for i in range(1, m + 1):
        cur = [i] + [0] * n
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]: cur[j] = prev[j - 1]
            else: cur[j] = 1 + min(prev[j], cur[j - 1], prev[j - 1])
        prev = cur
    return prev[n]

def longest_palindromic_subseq(s):
    return lcs(s, s[::-1])[0]
4

Longest Increasing Subsequence (LIS)

LIS is the longest strictly increasing subsequence of an array. O(n^2) DP: dp[i] = 1 + max(dp[j]) over j < i with a[j] < a[i]. O(n log n) method: maintain tails[k] = smallest possible tail of an increasing subsequence of length k+1 and binary search the position of each element.

In short: For each element, extend the best increasing run that ends below it; or keep the smallest tail for each length and binary search.

LIS: longest rising subsequence

Think about it

Shows the jump from O(n^2) DP to O(n log n) with binary search, a common follow-up in interviews.

Quadratic DP: dp[i] = length of LIS ending at i; answer = max(dp).

Reconstruct with a parent array.

Patience-sorting approach: for x, find the first index p in tails with tails[p] >= x (bisect_left for STRICT increasing; bisect_right for non-decreasing), set tails[p] = x or append when p == len(tails); len(tails) is the LIS length, but the tails array itself is NOT necessarily an actual LIS (store predecessor indices to reconstruct).

Complexity O(n log n) time, O(n) space.

Counting the number of LIS needs the O(n^2) DP with counts (or a BIT).

Related: longest non-decreasing subsequence, longest bitonic subsequence (LIS from left + LDS from right), minimum deletions to make the array sorted = n - LIS, Russian doll envelopes (sort by width ascending and height descending, then LIS on heights), maximum sum increasing subsequence (replace +1 by +a[i]), LIS = LCS(a, sorted unique a).

Number of piles in patience sorting = LIS length (Dilworth-like duality with the longest non-increasing subsequence).

Edge cases: empty array (0), all equal (1 for strict), strictly decreasing (1).

Key points

  • Tails array: tails[k] is the minimum tail value of any increasing subsequence of length k+1.
  • bisect_left: First position where tails[p] >= x (used for strict LIS).
  • Patience sorting: Card-pile analogy giving LIS length as number of piles.

Example

Code
LIS in two complexities:
from bisect import bisect_left

def lis_n2(a):                         # O(n^2)
    n = len(a)
    if n == 0: return 0
    dp = [1] * n
    for i in range(n):
        for j in range(i):
            if a[j] < a[i]:
                dp[i] = max(dp[i], dp[j] + 1)
    return max(dp)

def lis_nlogn(a):                      # O(n log n)
    tails = []
    for x in a:
        p = bisect_left(tails, x)      # strictly increasing
        if p == len(tails): tails.append(x)
        else: tails[p] = x
    return len(tails)

def lis_sequence(a):                   # with reconstruction
    tails, idx = [], []                # idx[k] = index in a of tails[k]
    prev = [-1] * len(a)
    for i, x in enumerate(a):
        p = bisect_left(tails, x)
        if p == len(tails): tails.append(x); idx.append(i)
        else: tails[p] = x; idx[p] = i
        prev[i] = idx[p - 1] if p else -1
    out, k = [], idx[-1] if idx else -1
    while k != -1: out.append(a[k]); k = prev[k]
    return out[::-1]

def min_deletions_sorted(a):
    return len(a) - lis_nlogn(a)

Solved examples

Example 01 · Basic

Minimum coins for amount 6 with coins {1, 3, 4}. Does greedy work?

Given Data:
    Required To Find:

    Answer

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: dp[0]=0, dp[1]=1, dp[2]=2, dp[3]=1, dp[4]=1, dp[5]=min(dp[4]+1, dp[2]+1)=2, dp[6]=min(dp[5]+1, dp[3]+1, dp[2]+1) = 2.
    Step 2: Greedy picks 4 then 1+1 = 3 coins.
    Final Answer: 2 coins (3+3); greedy gives 3 so DP is required

    Approach note: Greedy-choice property fails for arbitrary coin systems.

    Example 02 · Intermediate

    LCS of "ABCBDAB" and "BDCABA" (length and one LCS).

    Given Data:
      Required To Find:

      Length and string

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Fill dp using match -> diagonal+1 else max(up, left).
      Step 2: dp[7][6] = 4.
      Step 3: Trace back: one result is "BCBA" (others: "BDAB", "BCAB").
      Final Answer: Length 4, e.g. BCBA

      Approach note: LCS is not unique; the length is.

      Example 03 · Advanced

      Knapsack W=7, weights [1,3,4,5], values [1,4,5,7]. Best value?

      Given Data:
        Required To Find:

        Max value

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Start dp[0..7] = 0. Item (1,1): dp = [0,1,1,1,1,1,1,1].
        Step 2: Item (3,4): dp = [0,1,1,4,5,5,5,5].
        Step 3: Item (4,5): dp[7]=max(5, dp[3]+5=9)=9, dp[6]=max(5, dp[2]+5=6)=6, dp[5]=max(5, dp[1]+5=6)=6, dp[4]=max(5,5)=5 -> [0,1,1,4,5,6,6,9].
        Step 4: Item (5,7): dp[7]=max(9, dp[2]+7=8)=9.
        Final Answer: 9 (items with weights 3 and 4)

        Approach note: Iterating capacity upward here would wrongly reuse items.

        Example 04 · Basic

        Climbing stairs: n = 4 steps, can climb 1 or 2 at a time. How many distinct ways?

        Given Data:
          Required To Find:

          Number of ways

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: ways(n) = ways(n-1) + ways(n-2)
          Step 2: ways(1)=1, ways(2)=2
          Step 3: ways(3)=3, ways(4)=5
          Final Answer: 5 ways

          Approach note: Same recurrence as Fibonacci with different base cases.

          Real-world applications

          DSA

          Using Dynamic Programming (DP) in real projects

          Resource allocation, diff tools (LCS), spell correction (edit distance), sequence alignment in bioinformatics, route optimization.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: DP is just recursion with caching, so any recursive problem can use it.

          Why this is wrong: Needs overlapping subproblems and optimal substructure; plain divide and conquer (merge sort) has no overlap.

          ✅ Verified Truth: Check that the same states repeat before applying DP.

          ⚠️ Exam Tip: Draw the recursion tree and look for repeated nodes.

          ❌ Myth: 0/1 knapsack O(nW) is polynomial time.

          Why this is wrong: W is a number; input length is log W bits, so runtime is exponential in input size.

          ✅ Verified Truth: It is pseudo-polynomial, and the problem is NP-complete.

          ⚠️ Exam Tip: GATE trap question.

          ❌ Myth: In the O(n log n) LIS, the tails array is the LIS.

          Why this is wrong: Replacements overwrite tails and may produce an order not present in the input.

          ✅ Verified Truth: Only its length equals the LIS length; track predecessors to rebuild.

          ⚠️ Exam Tip: Test [2,5,3,7,11,8,10,13,6].

          Revision notes

          Dynamic programming solves problems with optimal substructure and overlapping subproblems by storing results: top-down memoization or bottom-up tabulation. It converts exponential recursion into polynomial time.

          High-Yield Quick Revision Points

          1. DP = optimal substructure + overlapping subproblems; time = states x transitions
          2. Memo (top-down, lazy) vs table (bottom-up, space-optimizable)
          3. Knapsack: dp[c]=max(dp[c], dp[c-w]+v) with c descending; O(nW) pseudo-polynomial
          4. LCS: match -> diag+1 else max(up,left); edit distance = 1 + min(3)
          5. LIS: O(n^2) dp or O(n log n) tails + bisect_left

          Practice questions

          Question 1 · MCQ (GATE)

          Time to compute LCS of lengths m and n with DP:

          Question 2 · MCQ (Interview)

          1-D 0/1 knapsack must iterate capacity:

          Question 3 · MCQ (Interview)

          LIS in O(n log n) uses:

          Question 4 · MCQ (GATE)

          Number of distinct subproblems in naive-memoized Fibonacci(n):

          Question 5 · MCQ (GATE)

          Minimum insertions + deletions to convert X to Y (lengths m, n):