Searching for a word inside a long text is one of the most common jobs a computer does. The simple method compares the pattern at every position, which can take O(n × m) time. In the KMP lesson you saw one way to do better. This lesson shows two more: Rabin-Karp, which compares numbers (hashes) instead of strings, and the Z algorithm, which measures how much of the pattern matches at every position in linear time.
In this lesson you will learn
- How a rolling hash turns a window of text into a number
- How to update the hash in O(1) when the window slides
- What a spurious hit is and why we still compare characters
- What the Z-array is and how to build it in O(n)
- How to search for a pattern with the Z-array
You should know strings in C and hashing.
Rabin-Karp: Rolling Hash
Treat each string of length m as a number in base 256 (one “digit” per character) and keep it small by taking the remainder modulo a prime. If two windows have different hashes, they cannot be equal. If the hashes are the same, we check the characters.
The key trick is that the next window’s hash can be found from the current one in O(1):
new hash = (BASE × (old hash − first char × BASE^(m−1)) + next char) mod MOD
#include <stdio.h>
#include <string.h>
#define BASE 256
#define MOD 13 /* a tiny prime, so collisions are easy to see */
/* Rabin-Karp: compare hashes first, then characters only when hashes match */
static void rabin_karp(const char *text, const char *pat) {
int n = (int)strlen(text), m = (int)strlen(pat);
int h = 1; /* BASE^(m-1) % MOD */
for (int i = 0; i < m - 1; i++) h = (h * BASE) % MOD;
int hp = 0, ht = 0;
for (int i = 0; i < m; i++) {
hp = (hp * BASE + pat[i]) % MOD;
ht = (ht * BASE + text[i]) % MOD;
}
printf("pattern hash = %d\n", hp);
for (int s = 0; s <= n - m; s++) {
if (hp == ht) {
if (strncmp(text + s, pat, (size_t)m) == 0) printf(" match at %d\n", s);
else printf(" hash hit at %d, but characters differ (spurious)\n", s);
}
if (s < n - m) { /* roll: drop text[s], add text[s+m] */
ht = (BASE * (ht - text[s] * h) + text[s + m]) % MOD;
if (ht < 0) ht += MOD;
}
}
}
int main(void) {
rabin_karp("abracadabra", "abra");
printf("\n");
rabin_karp("the cat sat on the mat", "at");
return 0;
}
Output
pattern hash = 6
match at 0
match at 7
pattern hash = 1
match at 5
hash hit at 8, but characters differ (spurious)
match at 9
hash hit at 14, but characters differ (spurious)
match at 20
hholds BASEm−1 mod MOD, the weight of the first character in the window. Subtractingtext[s] * hremoves that character.- In C,
%can give a negative result, so we add MOD when the hash goes below zero. - We chose a tiny MOD of 13 on purpose. With only 13 possible hashes, the windows “sa” (at 8) and ” t” (at 14) have the same hash as “at”. These spurious hits are caught by
strncmp. - Real programs use a large prime such as 1 000 000 007, so collisions are very rare. Then the average time is O(n + m), although the worst case is still O(n × m).
The Z Algorithm
For a string s, z[i] is the length of the longest substring starting at position i that matches the beginning (prefix) of s.
#include <stdio.h>
#include <string.h>
/* Z-array: z[i] = length of the longest substring starting at i
that is also a prefix of s */
static void z_array(const char *s, int n, int *z) {
z[0] = n;
int l = 0, r = 0; /* [l, r) is the rightmost match window */
for (int i = 1; i < n; i++) {
z[i] = 0;
if (i < r) z[i] = (r - i < z[i - l]) ? r - i : z[i - l]; /* reuse earlier work */
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++;
if (i + z[i] > r) { l = i; r = i + z[i]; }
}
}
int main(void) {
const char *s = "aabxaab";
int n = (int)strlen(s), z[64];
z_array(s, n, z);
printf("s: ");
for (int i = 0; i < n; i++) printf("%2c", s[i]);
printf("\nz: ");
for (int i = 0; i < n; i++) printf("%2d", z[i]);
printf("\n\n");
/* Pattern search: build pattern + '$' + text and look for z == m */
const char *pat = "ana", *text = "bananarama";
char buf[128];
snprintf(buf, sizeof buf, "%s$%s", pat, text);
int m = (int)strlen(pat), len = (int)strlen(buf), zz[128];
z_array(buf, len, zz);
printf("\"%s\" in \"%s\" at:", pat, text);
for (int i = m + 1; i < len; i++)
if (zz[i] == m) printf(" %d", i - m - 1);
printf("\n");
return 0;
}
Output
s: a a b x a a b
z: 7 1 0 0 3 1 0
"ana" in "bananarama" at: 1 3
- In “aabxaab”, z[4] = 3 because “aab” starting at 4 matches the prefix “aab”.
- The algorithm keeps a window [l, r) of the rightmost match found so far. Inside it, s[i] is a copy of s[i − l], so z[i − l] gives a free starting value. It then only extends past r with new comparisons.
- The pointer r only moves right, so the total work is O(n).
- To search, join pattern + “$” + text. The “$” never appears in either string, so no match can run across it. Wherever z equals the pattern length, the pattern occurs. “ana” appears at positions 1 and 3 of “bananarama”, and the two matches overlap.
Comparing String Algorithms
| Method | Time | Best used for |
|---|---|---|
| Naive | O(n × m) | Very short patterns |
| KMP | O(n + m) | One pattern, guaranteed linear time |
| Z algorithm | O(n + m) | One pattern; also prefix questions about a string |
| Rabin-Karp | O(n + m) on average | Many patterns of the same length; finding repeated substrings |
Rabin-Karp shines when you have many patterns: store all their hashes in a hash table and slide one window over the text. Plagiarism checkers use this idea to compare documents.
Common Mistakes
- Skipping the character check after a hash match, which reports false matches.
- Forgetting to fix negative remainders after the subtraction.
- Integer overflow in the hash: use
long longwith a big prime. - Using a separator that appears in the text when building pattern + “$” + text.
Practice Exercises
Exercise 1. Write the Z-array of “aaaa”.
Show answer
{4, 3, 2, 1}. From each position, the rest of the string is all a’s and matches the prefix.
Exercise 2. How can Rabin-Karp check whether a string has any repeated substring of length k?
Show answer
Slide a window of length k, compute each rolling hash, and store it in a hash set. If a hash is already in the set, compare the two windows’ characters to confirm the repeat.
Frequently Asked Questions
Why use a prime modulus?
A prime spreads the hash values more evenly, so different strings are less likely to collide. Using two different primes at once (double hashing) makes collisions almost impossible.
Is the Z-array related to KMP’s failure function?
Yes. Both describe how the string matches its own prefix, and each can be built from the other. Many people find the Z-array easier to understand.
Summary
- Rabin-Karp compares rolling hashes and checks characters only on a hash match.
- The rolling update removes the first character and adds the next one in O(1).
- z[i] is the longest prefix match starting at i; the whole array takes O(n).
- Search with Z by scanning pattern + “$” + text for z = m.
