Advanced Topic 44 of 51 Algorithms
Rabin-Karp Algorithm
String search using rolling hashes.
How it works
Rabin-Karp searches for a pattern by comparing hash values of the pattern and each window of the text. A rolling hash updates the hash of the next window in O(1) by removing the leading character and adding the next, so the average time is O(n + m). When hashes match, the characters are compared to rule out collisions.
Step-by-step walkthrough
- Compute a hash of the pattern.
- Hash the first text window of the same length.
- Sliding by one character updates the hash in O(1) by removing the old letter and adding the new one.
- If hashes differ, the window cannot match.
- If hashes match compare the characters to rule out a collision.
Where it is used
Plagiarism detection, searching for many patterns of the same length at once, finding duplicate chunks in files, two-dimensional pattern matching and content-defined chunking in backups use Rabin-Karp.
Common pitfall
A weak or small modulus gives many false matches and can degrade to O(nm). Forgetting to verify the match after a hash hit yields wrong results. Negative values after subtracting need modular adjustment. Choose a large prime modulus and a good base, and consider double hashing against adversarial inputs.
Where it fits in the course
Rabin-Karp Algorithm is topic 44 of 51 in Algorithms, rated Advanced. It follows KMP Algorithm. The next topic is Huffman Coding.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Algorithms quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Algorithms quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Rabin-Karp Algorithm?
Where do people use Rabin-Karp Algorithm?
What is the most common mistake with Rabin-Karp Algorithm?
What should I learn before this topic?
How can I practice it?
Is Rabin-Karp Algorithm hard to learn?
How long does it take to learn Rabin-Karp Algorithm?
Which topics are related to Rabin-Karp Algorithm?
What should I study after Rabin-Karp Algorithm?
Related topics
- KMP Algorithm (Algorithms)
- Huffman Coding (Algorithms)
- Maximum Flow (Algorithms)
- Randomized Algorithms (Algorithms)
- Shor's Algorithm (Emerging & Frontier Topics)
- Grover's Algorithm (Emerging & Frontier Topics)