Day 57: Rabin-Karp Algorithm
Day 57: Rabin-Karp Algorithm#
Welcome to Day 57 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore the Rabin-Karp algorithm, another efficient string matching algorithm that uses hashing to find patterns in text.
What is the Rabin-Karp Algorithm?#
The Rabin-Karp algorithm is a string-searching algorithm that uses hashing to find patterns in strings. It was created by Richard M. Karp and Michael O. Rabin in 1987. The algorithm is particularly useful for multi-pattern search.
How Rabin-Karp Works#
The key ideas behind the Rabin-Karp algorithm are:
- Use a hash function to convert the pattern and substrings of the text to numeric values.
- Compare the hash values instead of comparing the strings character by character.
- If the hash values match, then perform a character-by-character comparison to confirm the match.
The algorithm uses a rolling hash function, which allows it to efficiently compute hash values for subsequent substrings.
Implementation#
Here’s a Python implementation of the Rabin-Karp algorithm:
1def rabin_karp(text, pattern):
2 n = len(text)
3 m = len(pattern)
4 d = 256 # number of characters in the input alphabet
5 q = 101 …Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating