3.7.6 · HinglishAlgorithm Paradigms

Dynamic programming — overlapping subproblems, optimal substructure

1,638 words7 min readRead in English

3.7.6 · Coding › Algorithm Paradigms


DP exist kyun karta hai?

Plain recursion aksar same cheez ko exponentially zyada baar recompute karta hai. DP usi waste ko khatam karne ke liye exist karta hai.


DO properties (DP use karne se pehle DONO verify karna ZAROORI hai)


Recursion ko DP mein kaise badlein — do styles

Speedup ko first principles se derive karna

Figure — Dynamic programming — overlapping subproblems, optimal substructure

Worked Example 1 — Fibonacci, teen tarike se

Naive recursion ():

def fib(n):
    if n < 2: return n
    return fib(n-1) + fib(n-2)

Memoization (top-down):

def fib(n, memo={}):
    if n < 2: return n
    if n in memo: return memo[n]      # reuse — kills overlap
    memo[n] = fib(n-1, memo) + fib(n-2, memo)
    return memo[n]

Yeh step kyun? if n in memo check ek exponential tree ko ek linear chain mein convert kar deta hai: har ek baar compute hota hai, phir cache se serve hota hai.

Tabulation (bottom-up):

def fib(n):
    if n < 2: return n
    dp = [0, 1]
    for i in range(2, n+1):
        dp.append(dp[i-1] + dp[i-2])   # smallest → largest
    return dp[n]

Yeh step kyun? Hum increasing mein fill karte hain taaki pehle se computed hon — yahi ordering exactly "optimal substructure ko concrete banana" hai.


Worked Example 2 — 0/1 Knapsack (dono properties dikhate hue)

Items jinke weight , value hai, capacity hai. Value maximize karo.

Recurrence derive karo. Item ko remaining capacity ke saath socho. Do choices hain:

  1. Skip karo: best value hai .
  2. Lo (sirf tab agar ): gain karo + baaki ka best kam room ke saath: .

Yeh optimal substructure kyun hai? Items ki best packing mein zaroori hai ki baaki bachi capacity ke liye ki best packing ho — warna hum us better sub-packing ko swap karke poore ko improve kar sakte the. Overlap kyun hai? Kaafi alag item-prefixes same pair tak pahunchte hain.

def knapsack(w, v, W):
    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]                       # skip
            if w[i-1] <= c:
                dp[i][c] = max(dp[i][c],
                               v[i-1] + dp[i-1][c-w[i-1]])  # take
    return dp[n][W]

Time subproblems .


Steel-manned mistakes


Recall Feynman: ek 12-saal ke bacche ko explain karo

Socho ek homework jisme wahi chhota math problem 50 baar aata hai. Ek lazy-lekin-smart baccha use ek baar solve karta hai, jawab ek sticky note pe likhta hai, aur baaki 49 baar sirf copy karta hai. Yahi memoization hai. Tabulation mein pehle saare chhote problems karo, order mein, bade wale se pehle — jaise Lego ko neeche ke blocks se upar ki taraf banao. Trick tabhi kaam karti hai kyunki (1) wohi chhote problems baar baar repeat hote hain, aur (2) bada answer genuinely chhote answers se bana hota hai.


Flashcards

DP apply karne ke liye problem mein kaunsi do properties chahiye?
Overlapping subproblems aur optimal substructure.
Overlapping subproblems define karo.
Jab recursive solution ek hi subproblem ko kaafi baar revisit kare.
Optimal substructure define karo.
Jab poore ka optimal solution uske subproblems ke optimal solutions se build ho sake.
Memoization aur tabulation mein kya fark hai?
Memoization top-down hai (recursion + cache, lazy); tabulation bottom-up hai (iterative table fill, eager).
DP time complexity ka general formula?
(distinct subproblems ki sankhya) × (work per subproblem).
Fibonacci: naive vs DP time complexity?
Naive vs DP .
Merge Sort ko DP se faayda kyun nahi hota?
Uske subproblems sab distinct hain — koi overlapping subproblems nahi hain jo cache ho sakein.
0/1 knapsack ke liye greedy fail kyun hota hai lekin DP kaam karta hai?
0/1 knapsack mein greedy-choice property nahi hai; DP ko sirf optimal substructure chahiye, jo uske paas hai.
Ek aise problem ka example do jisme overlap ho lekin optimal substructure NA ho.
Graph mein longest simple path (sub-paths nodes reuse nahi kar sakte), toh DP/memoization galat answers deta hai.
Tabulation ko kaunsa ordering rule follow karna chahiye?
Subproblems ko uss order mein fill karo jahan har dependency read hone se pehle already computed ho.
0/1 Knapsack recurrence?
K(i,c)=max(K(i-1,c), v_i+K(i-1,c-w_i)) jab w_i≤c, warna K(i-1,c).
0/1 knapsack DP ki time complexity?
O(nW), n items × W capacity subproblems.

Connections

  • Recursion — DP memory-augmented recursion hai.
  • Divide and Conquer — subproblems disjoint hain (koi overlap nahi) → DP nahi.
  • Greedy Algorithms — greedy-choice property chahiye; DP ko sirf optimal substructure chahiye.
  • Memoization vs Tabulation
  • Knapsack Problem, Longest Common Subsequence, Bellman-Ford
  • Time Complexity Analysis
  • Recursion Trees

Concept Map

leads to

motivates

requires

requires

makes caching worth it

makes building correct

if absent

unique subproblems means

implemented via

implemented via

store each answer once

fill table in order

yields

Plain recursion

Recomputes same subproblems

Dynamic Programming

Overlapping subproblems

Optimal substructure

Memoization top-down

Tabulation bottom-up

Time = distinct subproblems x work each

O 2^n down to O n

Divide and Conquer