String Hashing
Authors: Benjamin Qi, Andi Qu
Contributors: Andrew Wang, Kevin Sheng
Quickly test equality of substrings with a small probability of failure.
Prerequisites
Tutorial
Resources | ||||
---|---|---|---|---|
CPH | good intro | |||
cp-algo | code | |||
PAPS | many applications |
Optional
If "small" isn't a satisfying-enough answer for "what's the probability of collision?", then you should check out rng-58's blog post talking about hashing. This blog post talks about the Schwarz-Zippel lemma and how that can be used to calculate the probability of a collision.
It also explains how to hash rooted trees - an uncommon technique, but still useful to know!
Implementation - Single Base
As mentioned in the articles above, there is no need to calculate modular inverses.
C++
#include <vector>#include <string>using namespace std;class HashedString {private:// change M and P if you wantstatic const long long M = 1e9 + 9;static const long long P = 9973;
Java
import java.util.*;public class HashedString {// Change M and P if you wantpublic static final long M = (long) 1e9 + 9;public static final long P = 9973;// pow[i] contains P^i % Mprivate static ArrayList<Long> pow = new ArrayList<>();
Python
class HashedString:# Change M and P if you wantM = int(1e9) + 9P = 9973# pow[i] contains P^i % M_pow = [1]def __init__(self, s: str):while len(self._pow) < len(s):
This implementation calculates
The hash of any particular substring is then calculated as
using prefix sums. This is nice because the highest power of in that polynomial will always be .
Since is prime, the probability of collision when using this hash is at most , by the Schwarz-Zippel lemma. This means that if you select any two different strings of length at most and a random base modulo (e.g. in the code), the probability that they hash to the same value is at most .
Implementation - Multiple Bases
Resources | ||||
---|---|---|---|---|
CF | regarding CF educational rounds in particular | |||
Benq |
It's generally a good idea to use two randomized bases rather than just one to decrease the probability that two random strings hash to the same value.
Focus Problem – read through this problem before continuing!
Solution - Searching For Strings
One Hash
Time Complexity: , where is the size of the alphabet.
We'll use a sliding window over to find the "matches" with .
Since we don't care about relative order when comparing two substrings, we can store frequency tables of the characters in the current window and in . When we slide the window, at most two values in that table change. To compare two substrings, we simply compare the 26 values in each table.
If we only needed to count the number of matches, then the above alone would suffice (in fact, IOI 2006 Writing is just that). However, we need to count the distinct permutations of in , so we need to be a bit more clever.
One way to solve this is by storing the polynomial hashes of each match in a hashset, since we expect different permutations to have different polynomial hashes. The answer would simply be the size of that hashset at the end.
Since the test data for this particular problem is very strong, we will probably get hash collisions with only one hash. To remedy this, we use two hashes for each match - this significantly decreases the probability of collisions.
Using the base with the two modulos and works for this problem. (Note that using two bases with the same modulo works too.)
C++
#include <bits/stdc++.h>typedef long long ll;using namespace std;const ll P = 9973, M1 = 1e9 + 9, M2 = 1e9 + 7;int freq_target[26], freq_curr[26];string n, h;int main() {
Two Hashes
Time Complexity:
An alternative solution without frequency tables would be to hash the substrings that we're trying to match. Since order doesn't matter, we need to modify our hash function slightly.
In particular, instead of computing the polynomial hash of the substrings, compute the product as the hash (again, using two modulos). This hash is nice because the relative order of the letters doesn't matter, as multiplication is commutative.
Since this hash requires the modular inverse, there's an extra factor in the time complexity.
Alternative hashes (e.g. computing the sum ) also work for other hashing problems, but the test cases are too strong for that to pass here.
C++
#include <bits/stdc++.h>typedef long long ll;using namespace std;const ll P = 9973, M1 = 1e9 + 9, M2 = 1e9 + 7;ll inv(ll base, ll MOD) {ll ans = 1, expo = MOD - 2;while (expo) {if (expo & 1) ans = ans * base % MOD;
Problems
Status | Source | Problem Name | Difficulty | Tags | |
---|---|---|---|---|---|
CEOI | Easy | Show TagsGreedy, Hashing | |||
CF | Easy | Show TagsDP, Hashing | |||
CF | Easy | Show TagsHashing | |||
Gold | Normal | Show TagsHashing | |||
Gold | Normal | Show TagsHashing, Simulation | |||
RMI | Normal | Show TagsHashing | |||
COCI | Normal | Show TagsHashing, Probability | |||
COCI | Hard | Show TagsBinary Search, Hashing | |||
CF | Hard | Show TagsDP, Hashing | |||
Baltic OI | Hard | Show TagsHashing | |||
COCI | Very Hard | Show TagsDSU, Hashing | |||
COI | Very Hard | Show TagsBinary Search, Hashing |