Exercises — DP problems — edit distance (Levenshtein)
3.7.12 · D4· Coding › Algorithm Paradigms › DP problems — edit distance (Levenshtein)
Poore time, ek hi object yaad rakho jisko hum fill kar rahe hain:
Aur ek rule jo ise fill karta hai:

Upar ki picture poore page ke liye mental compass hai: ↖ diagonal do letters compare karta hai, ↑ upar matlab se delete, ← left matlab mein insert. Isko baar baar dekhte rehna.
Level 1 — Recognition
(Kya tum sahi machinery spot kar sakte ho?)
L1.1
Kisi bhi do strings ke liye batao, aur words mein explain karo kyun.
Recall Solution
. Row ka matlab hai "string zero letters contribute kar rahi hai" — woh empty hai. ke pehle 4 letters kuch nahi se banana ho, toh sirf insert ka move kaam aata hai jo letters add karta hai, aur tumhe exactly 4 chahiye. Koi sasta route nahi hai, isliye yeh ek base case hai, computed cell nahi.
L1.2
'k' aur 'k' diya hai, toh teen neighbours mein se kaunsa copy karta hai, aur kya koi hai?
Recall Solution
Letters match karte hain, isliye : pure diagonal, koi nahi. Ek letter match karna free hai — tum is position pe na insert karte ho, na delete, na substitute.
L1.3
Har neighbour kaun sa operation encode karta hai, naam batao:
- (seedha upar wala cell)
- (seedha left wala cell)
- (diagonal, jab letters differ karte hain)
Recall Solution
- → se ek letter delete karo ( ka prefix ek se chota hua, ka wahi raha).
- → mein ek letter insert karo ( ka prefix chota hua, matlab ko woh extra letter chahiye tha).
- (differing letters) → substitute (dono prefixes chote hue aur letter swap karne ki cost di).
Level 2 — Application
(Crank sahi se ghao.)
L2.1
ko last letters ke baare mein reason karke compute karo (poora table nahi chahiye).
Recall Solution
Right-to-left align karo. 't'='t' → free. 'a' vs 'u' → differ, ek substitute (+1). 'c'='c' → free. Total .
L2.2
ke liye poora table fill karo aur answer do.
Recall Solution
abc (rows), yabd (cols).
| "" | y | a | b | d | |
|---|---|---|---|---|---|
| "" | 0 | 1 | 2 | 3 | 4 |
| a | 1 | 1 | 1 | 2 | 3 |
| b | 2 | 2 | 2 | 1 | 2 |
| c | 3 | 3 | 3 | 2 | 2 |
Bottom-right . Path: aage y insert karo (+1), phir a,b free mein match, phir c→d substitute karo (+1). Ek insert + ek substitute = 2.
L2.3
compute karo.
Recall Solution
Har letter 'a' hai, toh kabhi koi substitution nahi chahiye — matches cost ko seedha diagonal se neeche le jaate hain. Sirf fark length mein hai: ke paas do extra 'a' hain. Dono delete karo → . (Yahan yeh exactly length difference ke barabar hai kyunki koi letter kabhi change nahi karna pada.)
Level 3 — Analysis
(Explain karo kyun ek cell apni value hold karta hai.)
L3.1
ke table mein (parent note se), aaya tha se. Kaun sa operation jeeta, aur physically iska kya matlab hai?
Recall Solution
Jeetnewala neighbour hai (seedha upar wala cell). "Upar" ek delete from encode karta hai: hum horse ka trailing 'e' delete karte hain. Toh optimal path ka last move hai delete e, aur bacha hua cost 2 hors→ros fix karta hai. Baaki do options (substitute via , insert via ) strictly zyada expensive the.
L3.2
Prove karo ki kisi bhi strings ke liye (edit distance symmetric hai).
Recall Solution
Har operation ka ek exact inverse of equal cost hota hai: mein ek letter ka insert undo hota hai us letter ke delete se (aur vice-versa); ek substitute x→y undo hota hai substitute y→x se. Toh koi bhi editing script jo ko mein moves mein turn karti hai, move-by-move reverse ho sakti hai ko mein same moves mein turn karne ke liye. Isliye ek taraf jo bhi cost achieve ho sakti hai woh doosri taraf bhi ho sakti hai, aur minimums equal hain: .
L3.3
Sirf lengths , use karke ka tightest lower bound do, aur explain karo yeh kyun hold karta hai.
Recall Solution
. Reason: sirf insert aur delete ek string ki length change karte hain, aur har ek use exactly 1 se change karta hai. Substitute length unchanged chhod deta hai. Length se length tak jaane ke liye tumhe isliye kam se kam length-changing moves chahiye. Toh lengths ka difference ek floor hai, neeche kabhi nahi jaata — lekin yeh sirf ek lower bound hai, kyunki substitutions length change kiye bina cost add karti hain. horse(5)→ros(3) ke liye: bound hai , lekin sahi answer 3 hai.
Level 4 — Synthesis
(Machinery ko combine aur adapt karo.)
L4.1
Maano substitution forbidden hai (sirf insert aur delete allowed, har ek cost 1). Nayi recurrence likho aur ke liye nayi distance compute karo.
Recall Solution
Substitution remove karne se min mein se "substitute" candidate delete ho jaata hai. Recurrence ban jaati hai:
Yeh exactly delete-both-then-reinsert cost hai, aur yeh Longest Common Subsequence se tied hai: distance .
cat→cut ke liye: LCS hai ct length 2 ka, toh distance . (Ek delete a ka, ek insert u ka — agar allowed hota toh single substitute se bhi ho jaata.)
L4.2
Ab substitution cost 2 karo jabki insert aur delete har ek cost 1 rahein. recompute karo aur decide karo kaun si strategy jeetti hai.
Recall Solution
Substitute term ka ko se replace karo:
Single mismatch a vs u ke liye: substitute cost 2, lekin delete-a + insert-u bhi cost hai — ek tie at . General rule: jab substitution cost ho, delete+insert hamesha kam se kam utna hi achha hai, toh substitution kabhi strictly nahi jeetti.
L4.3
Space Optimization in DP use karke, sirf do rows (previous aur current) rakhte hue compute karo. Har step pe dono rows dikhao aur answer do.
Recall Solution
ab (rows), ba (cols). Row 0 (base) hai .
Row 1 compute karo (A[0]='a'), sirf row 0 padhte hue:
- (base column).
- ,
'a'vs'b'differ karte hain → . - ,
'a'vs'a'match → diagonal .
Row 1 . Row 0 discard karo, row 1 ko "previous" rakhho.
Row 2 compute karo (A[1]='b'), sirf row 1 padhte hue:
- (base column).
- ,
'b'vs'b'match → diagonal prev. - ,
'b'vs'a'differ karte hain → .
Row 2 . Answer (ab→ba swap karne mein do edits lagte hain: dono substitute karo, ya delete+insert). Humhe kabhi poora grid nahi chahiye tha — do rows kaafi the kyunki recurrence sirf row padhti hai.
Level 5 — Mastery
(Invent karo, generalise karo, aur defend karo.)
L5.1
Ek colleague claim karta hai: "Agar aur mein bilkul koi common letter nahi, toh ." Prove ya disprove karo.
Recall Solution
Sach hai. Koi shared letter nahi hone se koi diagonal match kabhi free nahi hoga. Overlapping positions reconcile karne ka sabse sasta tarika hai unhe substitute karna (cost 1 each) pehle positions ke liye, phir baaki leftover letters ke liye insert ya delete karna (cost 1 each). Total . Koi route isse beat nahi kar sakta: tumhe saare positions account karne hain, aur har ek kam se kam 1 cost karta hai kyunki kuch match nahi karta. Toh .
L5.2
Ek verification test design karo: "x" (letter x baar repeat) aur "y" form ki strings ke liye, ek closed formula se predict karo aur justify karo.
Recall Solution
Har letter differ karta hai (x vs y), lengths equal hain, toh koi length change nahi chahiye aur aligned positions mein se har ek ko ek substitute chahiye. Closed form: . Check : "xxx"→"yyy" ko 3 substitutions chahiye . Yeh ek clean regression test hai kyunki answer exactly linearly ke saath scale karta hai.
L5.3
L2.2 se ka actual edit script (moves ki list) reconstruct karo bottom-right cell se backwards walk karke. Traceback rule explain karo.
Recall Solution
Traceback rule: har cell pe, dekho kaun se neighbour ne ise produce kiya.
- Start (
cvsd, differ). Yeh ke barabar hai diagonal se → substitutec→d. pe jao. - (
bvsb, match) → diagonal se aaya, koi move nahi. pe jao. - (
avsa, match) → diagonal , koi move nahi. pe jao. - row 0 pe hai → mein
yabhi bhi account karna hai → inserty. pe pohoncho. Ho gaya.
Forwards padhne par: insert y, a rakho, b rakho, substitute c→d → exactly 2 edits, table se match karta hai. Yahi traceback wajah hai ki poora grid store karna (sirf ek row ki jagah) worth it hai jab tumhe script chahiye, sirf number nahi.
Recall
Recall Quick self-check
sab costs 1 ke saath ::: 1
::: 2
::: 2
cat,cut ki insert-and-delete-only distance ::: 2 (equals )
Lengths se ka lower bound :::
::: 3
Jab strings mein koi common letter nahi toh distance :::
Connections
- Parent topic — woh full derivation jisko yeh exercises drill karti hain.
- Longest Common Subsequence — insert/delete-only variant (L4.1) LCS ka hi disguise hai.
- Space Optimization in DP — L4.3 ka two-row trick.
- Dynamic Programming, Optimal Substructure, Overlapping Subproblems, Recursion and Memoization, Sequence Alignment — yeh paradigm aur uske neighbours.