What if you could find a phrase in a huge book almost instantly without reading every word?
Why Rabin Karp String Matching in DSA Javascript?
Imagine you have a huge book and you want to find every place where a certain phrase appears. You try to read every page carefully and check each word one by one to see if it matches your phrase.
This manual way is very slow and tiring. Checking every word and phrase takes a lot of time, especially if the book is very big. You might also make mistakes by missing some matches or checking the same parts again and again.
Rabin Karp uses a smart trick: it turns each phrase into a number (called a hash) and compares these numbers instead of the whole phrase. This way, it quickly skips parts that don't match and only checks closely when the numbers match, saving a lot of time.
function manualSearch(text, pattern) {
for (let i = 0; i <= text.length - pattern.length; i++) {
if (text.substring(i, i + pattern.length) === pattern) {
console.log('Found at', i);
}
}
}function rabinKarpSearch(text, pattern) {
const prime = 101;
function hash(str, p) {
let h = 0;
const base = 31;
for (let j = 0; j < str.length; j++) {
h = (h * base + str.charCodeAt(j)) % p;
}
return h;
}
const patternHash = hash(pattern, prime);
for (let i = 0; i <= text.length - pattern.length; i++) {
const currentHash = hash(text.substring(i, i + pattern.length), prime);
if (currentHash === patternHash && text.substring(i, i + pattern.length) === pattern) {
console.log('Found at', i);
}
}
}It enables fast and efficient searching of patterns in large texts by quickly ignoring impossible matches.
Search engines use this method to quickly find your search words inside millions of web pages without reading every word carefully.
Manual searching is slow and error-prone for large texts.
Rabin Karp uses hashing to speed up pattern matching.
This method quickly skips non-matching parts and checks only likely matches.
Practice
Rabin Karp String Matching algorithm?Solution
Step 1: Understand Rabin Karp's approach
The algorithm uses a hash function to convert the pattern and substrings of the text into numbers.Step 2: Use hashing for efficient matching
By comparing hash values instead of characters, it quickly finds potential matches and then verifies them.Final Answer:
Use hashing to find pattern matches efficiently -> Option CQuick Check:
Rabin Karp = hashing for matching [OK]
- Thinking it uses recursion
- Assuming it sorts strings before matching
- Confusing it with brute force method
Solution
Step 1: Understand hash calculation formula
The rolling hash is computed by multiplying the current hash by base and adding the new character code, then taking modulo prime.Step 2: Match formula with options
hash = (hash * base + charCode) % prime matches the formula: hash = (hash * base + charCode) % prime.Final Answer:
hash = (hash * base + charCode) % prime -> Option BQuick Check:
Rolling hash formula = hash = (hash * base + charCode) % prime [OK]
- Adding base multiplied by charCode instead of multiplying hash
- Mixing up modulo operations
- Using wrong order of operations
const text = 'ababc';
const pattern = 'abc';
// Assume base=256, prime=101
// Simplified hash function and matching logic
function rabinKarp(text, pattern) {
const m = pattern.length;
const n = text.length;
for (let i = 0; i <= n - m; i++) {
if (text.substring(i, i + m) === pattern) {
return i;
}
}
return -1;
}
console.log(rabinKarp(text, pattern));Solution
Step 1: Check substring matches
Check substrings of length 3 in 'ababc': 'aba'(index 0), 'bab'(1), 'abc'(2).Step 2: Identify matching index
'abc' matches at index 2, so function returns 2.Final Answer:
2 -> Option AQuick Check:
Pattern found at index 2 [OK]
- Returning first partial match index
- Off-by-one errors in loop
- Confusing substring indices
function rabinKarp(text, pattern) {
const base = 256;
const prime = 101;
let patternHash = 0, textHash = 0;
const m = pattern.length;
const n = text.length;
let h = 1;
for (let i = 0; i < m; i++) {
h = (h * base) % prime;
}
for (let i = 0; i < m; i++) {
patternHash = (base * patternHash + pattern.charCodeAt(i)) % prime;
textHash = (base * textHash + text.charCodeAt(i)) % prime;
}
for (let i = 0; i <= n - m; i++) {
if (patternHash === textHash) {
if (text.substring(i, i + m) === pattern) {
return i;
}
}
if (i < n - m) {
textHash = (base * (textHash - text.charCodeAt(i) * h) + text.charCodeAt(i + m)) % prime;
if (textHash < 0) textHash += prime;
}
}
return -1;
}Solution
Step 1: Examine the h calculation
The variable h should be base^(m-1) % prime to multiply the outgoing character's contribution.Step 2: Identify the loop error
The loop runs from i=0 to iFinal Answer:
Incorrect calculation of h in the first loop -> Option DQuick Check:
h = base^(m-1) % prime requires loop m-1 times [OK]
- Forgetting to add prime if textHash becomes negative
- Incorrect loop range for h calculation
- Not verifying substring match after hash match
Solution
Step 1: Understand multiple pattern matching challenge
Checking each pattern separately is slow for many patterns.Step 2: Use hashing for all patterns
Precompute hashes of all patterns and store in a hash set for O(1) lookup during text scanning.Step 3: Efficiently find all matches
When scanning text substrings, compute hash and check if it exists in the pattern hash set to find matches quickly.Final Answer:
Precompute hashes of all patterns and use a hash set for quick lookup -> Option AQuick Check:
Multiple patterns = precompute hashes + hash set [OK]
- Checking each pattern separately causing slow performance
- Sorting patterns instead of hashing
- Using recursion unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
