Challenge - 5 Problems
Rabin Karp Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Rabin Karp hash calculation
What is the output of the following TypeScript code that calculates the initial hash for the pattern 'abc' using a simple rolling hash?
DSA Typescript
const base = 256; const prime = 101; const pattern = 'abc'; let hash = 0; for (let i = 0; i < pattern.length; i++) { hash = (hash * base + pattern.charCodeAt(i)) % prime; } console.log(hash);
Attempts:
2 left
💡 Hint
Calculate hash step by step using modulo arithmetic.
✗ Incorrect
The hash is calculated as (((0 * 256 + 'a') % 101) * 256 + 'b') % 101, then multiplied by 256 and added 'c' modulo 101. The final value is 90.
🧠 Conceptual
intermediateUnderstanding the rolling hash update in Rabin Karp
In Rabin Karp algorithm, when sliding the window over the text, how is the rolling hash updated to remove the leftmost character and add the new rightmost character?
Attempts:
2 left
💡 Hint
Think about removing the old character's contribution before adding the new one.
✗ Incorrect
The rolling hash removes the leftmost character's weighted value (left_char * base^(pattern_length-1)), multiplies the remaining hash by base, adds the new character's code, and then takes modulo prime.
🔧 Debug
advancedIdentify the error in this Rabin Karp hash update code
What error will the following TypeScript code produce when updating the rolling hash in Rabin Karp?
DSA Typescript
const base = 256; const prime = 101; const patternLength = 3; let highestBasePower = Math.pow(base, patternLength - 1) % prime; let oldHash = 94; const leftCharCode = 'a'.charCodeAt(0); const newCharCode = 'd'.charCodeAt(0); let newHash = (oldHash - leftCharCode * highestBasePower) * base + newCharCode % prime; console.log(newHash);
Attempts:
2 left
💡 Hint
Check operator precedence and modulo placement.
✗ Incorrect
The modulo operator is applied only to newCharCode, not the entire expression, causing the subtraction result to be negative and no modulo applied to the whole expression, leading to a negative hash.
🚀 Application
advancedNumber of pattern matches found by Rabin Karp
Given the text 'abracadabra' and pattern 'abra', how many matches will the Rabin Karp algorithm find?
Attempts:
2 left
💡 Hint
Look for all occurrences of 'abra' in the text.
✗ Incorrect
The pattern 'abra' appears twice in 'abracadabra': at the start (index 0) and near the end (index 7).
🧠 Conceptual
expertWhy does Rabin Karp use a prime number in hashing?
Why is a prime number used as the modulo base in the Rabin Karp rolling hash algorithm?
Attempts:
2 left
💡 Hint
Think about how modulo with prime affects distribution of values.
✗ Incorrect
Using a prime number as modulo helps spread hash values more uniformly, reducing collisions and improving algorithm efficiency.
