String Algorithms
Rabin-Karp Algorithm
An elegant string-searching algorithm that uses a rolling hash to quickly find a pattern within a text.
Rabin-Karp Implementation
This implementation demonstrates the rolling hash technique to efficiently search for a pattern in a text.
function rabinKarp(text, pattern) {
const d = 256; // number of characters in the input alphabet
const q = 101; // a prime number
const M = pattern.length;
const N = text.length;
let p = 0; // hash value for pattern
let t = 0; // hash value for text
let h = 1;
for (let i = 0; i < M - 1; i++) { h = (h * d) % q; }
for (let i = 0; i < M; i++) {
p = (d * p + pattern.charCodeAt(i)) % q;
t = (d * t + text.charCodeAt(i)) % q;
}
for (let i = 0; i <= N - M; i++) {
if (p === t) {
let match = true;
for (let j = 0; j < M; j++) {
if (text[i + j] !== pattern[j]) { match = false; break; }
}
if (match) return i;
}
if (i < N - M) {
t = (d * (t - text.charCodeAt(i) * h) + text.charCodeAt(i + M)) % q;
if (t < 0) t = t + q;
}
}
return -1;
}
AI Coach Hint: The main weakness of Rabin-Karp is spurious hits (when hash values match but the strings don't). The choice of prime number `q` and base `d` is crucial to minimize these collisions. Be ready to discuss how you would handle frequent collisions in an interview.
Related Algorithm Guides
Explore more algorithm interview guides powered by AI coaching
Floyds Cycle Detection Algorithm In Linked Lists
AI-powered interview preparation guide
Trie Data Structure Applications In Interviews
AI-powered interview preparation guide
Augmented Reality Engineer Interview Questions
AI-powered interview preparation guide
Ar Vr Developer Interview Questions
AI-powered interview preparation guide
Related Algorithm Resources
All Interview Solutions
Browse our complete collection of AI-powered interview preparation guides.
GeeksforGeeks Algorithms
Comprehensive algorithm tutorials and practice problems.
LeetCode Practice
Algorithm coding challenges and interview preparation.
Algorithm Visualizations
Interactive visualizations for understanding algorithms.