3.8.3 · D4 · HinglishString Algorithms

ExercisesRabin-Karp — rolling hash, O(n+m) expected

2,355 words11 min read↑ Read in English

3.8.3 · D4 · Coding › String Algorithms › Rabin-Karp — rolling hash, O(n+m) expected

Shuru karne se pehle, hum ek shared convention fix karte hain taaki koi bhi symbol kabhi unexplained na rahe:

Neeche wali figure woh ek picture hai jis par poora page depend karta hai — ise saamne raho.

Figure — Rabin-Karp — rolling hash, O(n+m) expected

Level 1 — Recognition

L1.1 — Digit weights pehchano

String "cat" () ke liye base ke saath, uske hash ke liye polynomial likho kisi bhi mod se pehle. Kaunsa character weight carry karta hai?

Recall Solution

KYA: hum ko term by term expand karte hain. KYUN: sabse baayi taraf wala character most significant digit hai, isliye woh ki sabse zyada power se multiply hota hai. Compute karo: , plus , plus . Pehla character c weight carry karta hai.

L1.2 — Hash mismatch se kya prove hota hai?

Tum compute karte ho aur ek window ka hash hai. Tum kya conclude kar sakte ho, aur tumhe kya karna chahiye?

Recall Solution

Conclude: strings definitely different hain. Equal strings hamesha equal hashes produce karti hain, isliye unequal hashes se unequal strings zaroori hain. Karo: is window ko instantly skip karo — koi bhi character check zaroori nahi hai. (Contrast: hash match ka matlab sirf "probably equal" hai, isliye usse verification ki zaroorat hoti hai.)


Level 2 — Application

L2.1 — Hash mod compute karo

compute karo ke saath.

Recall Solution

L1.1 se raw value hai. KYUN mod: hum ise chhota aur bounded rakhte hain. , kyunki aur .

L2.2 — Haath se ek roll karo

Text (), , , . Tumhare paas already hai. Drop, Slide, Add use karke , yaani window "ats" ka hash, compute karo.

Recall Solution

Precompute . Kyunki , . Drop leading c: . Non-negative rakho: . Slide () aur Add trailing s: . , isliye . Direct formula se check karo: ; . ✓ Roll aur direct computation agree karte hain — yahi poori baat hai.

L2.3 — Match position dhundo

mein search karo, , , . Har match ka index report karo.

Recall Solution

. Window 0 "aa" → skip. Window 1 "ab" pe roll karo: . . se match karta hai → verify karo → "ab"=="ab" ✓. Match at index 1.


Level 3 — Analysis

L3.1 — Chhota prime kyun dangerous hai

aur ke saath, do-letter strings "ac" () aur "ba" () hash karo. Kya woh collide karte hain? Running time ke liye consequence explain karo.

Recall Solution

. . Woh collide karte hain () bhaale strings alag hain. Consequence: chhote ke saath, bahut saari windows equal hashes produce karti hain, isliye hum verification baar baar chalate hain → "expected " worst case ki taraf collapse ho jaata hai. Isliye hum jaisa bada prime choose karte hain. Dekho Modular Arithmetic aur Birthday Paradox.

L3.2 — Collision probability reasoning

Ek achhe random hash mod prime ke saath, kisi bhi galat window ke collide hone ka chance lagbhag hai. Agar ek text mein windows hain aur , toh roughly kitne spurious verifications expect karte hain?

Recall Solution

KYUN yeh tool: expected count (number of trials) (per-trial probability), yeh linearity-of-expectation shortcut hai. Lagbhag har hazaar searches mein se sirf ek mein ek bhi wasted verification hoti hai — negligible. Isliye total expected cost rehta hai.

L3.3 — Worst case construct karo

Ek text/pattern family do (ek chosen ke saath) jo force kare. Explain karo kyun.

Recall Solution

Lo ( copies) aur ( copies). Har window ke equal hai, isliye har hash match karta hai aur har window ek full verification trigger karti hai. Total . Note karo yeh ek genuine-match worst case hai; ek adversarial collision worst case ki jagah ek known small use karta hai aur aisi alag windows craft karta hai jo sab pe hash karti hain. Dono average-case bound ko defeat karte hain. Isliye Knuth-Morris-Pratt (guaranteed ) prefer kiya jaata hai jab adversaries possible hon.


Level 4 — Synthesis

L4.1 — Two-hash defence

Tum do independent hashes aur use karte ho jahan , hain. Ek galat window dono pe tabhi collide karti hai jab woh har ek pe collide kare. Combined per-window false-positive rate estimate karo aur ek single hash mod se compare karo.

Recall Solution

KYUN independence multiply karta hai: do independent events dono tab hote hain jab probability product ke equal hoti hai. Combined rate . Ek single hash mod deta hai . Toh do chhote primes () already ek modulus of se better hain: . Lesson: do independent moduli apni protection multiply karte hain, isliye double hashing itna strong hai. Dekho String Hashing for Substring Comparison.

L4.2 — Ek real text pe full trace

mein search karo, , , . Saari windows trace karo aur match indices list karo.

Recall Solution

. . ke codes: .

  • Window 0 "ba": . → skip.
  • Roll → Window 1 "ab": drop b: ; slide+add b: . → verify "ab" ✓. Match at 1.
  • Roll → Window 2 "ba": drop a: ; slide+add a: . → skip.
  • Roll → Window 3 "ab": drop b: ; slide+add b: . → verify ✓. Match at 3. Matches: indices 1 aur 3. (Direct check: babab[1..2]=ab, [3..4]=ab. ✓)

Level 5 — Mastery

L5.1 — Ek robust searcher design karo

Tumhe ek untrusted user (possible adversary) ke dwara supply kiye gaye text mein ek pattern search karna hai, near-guaranteed correctness aur achhi speed chahiye. Apna poora design batao aur har choice ko un failure modes ke khilaf justify karo jo tumne seekhe.

Recall Solution

Design:

  1. Double hashing use karo: do random large primes , random bases . Kyun: combined collision rate — yahan tak ki ek crafted adversary random bases predict nahi kar sakta, isliye L3.3 ka collision attack fail ho jaata hai.
  2. Har hash ke liye ek baar precompute karo. Kyun: loop ke andar recomputing karne se har roll ho jaata hai aur speedup khatam ho jaata hai (scale pe L2 precompute mistake).
  3. Subtraction ko ((x)%q+q)%q se guard karo. Kyun: negative-hash corruption rokta hai (L2 trap).
  4. (Double) hash hit pe char-by-char verify karna jaari rakho. Kyun: correctness ko exact rakhta hai, aur double hashing ke saath verifications essentially sirf true matches pe hoti hain, isliye expected time rehta hai.
  5. Fallback: agar guaranteed worst-case mandate hai (jaise hard real-time), toh Knuth-Morris-Pratt ya Z-Algorithm pe switch karo, jinhe koi randomness ki zaroorat nahi.

L5.2 — Roll ko algebraically prove karo

Dikhao ki Drop-Slide-Add formula exactly produce karta hai, mod ignore karke. Hum actually mod ko valid banane ke liye kahan chahiye?

Recall Solution

Likho . Leading term hai . Drop: . Slide (): . se re-index karo: — yeh ka hash hai lekin uska aakhri character missing hai aur har weight ek power zyada high hai... precisely, yeh ke pehle terms ke barabar hai. Add : final low-order digit fill karta hai, deta hai . ∎ Mod validity: addition, subtraction, aur multiplication sab "" ke saath commute karte hain — yeh Modular Arithmetic ka ek theorem hai. Isliye har step mod karne se wahi remainder milta hai jaise pehle bada number compute karo aur end mein reduce karo. Division mod ke saath survive nahi karta, isliye hamare hash mein sirf use hota hai.


Recall Ek-line self-test

Rolling update formula ::: Double-hash hit ke baad verification kyun rakhein? ::: Exactly correct rehne ke liye; rare/adversarial collision hi woh cheez hai jo "probably equal" aur "equal" ke beech khadi hai.

Connections

  • Rabin-Karp — rolling hash, O(n+m) expected — parent theory jin pe yeh drills exercise karti hain
  • Hashing — polynomial/modular hash foundations jo poore mein use hoti hain
  • Modular Arithmetic — kyun mod ke saath survive karte hain lekin division fragile hai (L5.2, L2 traps)
  • Birthday Paradox — collision-probability intuition L3.2 ke peeche
  • Knuth-Morris-Pratt, Z-Algorithm — worst-case-guaranteed fallbacks (L3.3, L5.1)
  • String Hashing for Substring Comparison — L4.1 se double-hashing idea