Counting hash collisions with the birthday paradox
Let be the number of days in the year.
For real birthdays, would be 365, but for hashing, is the size of the range of the hash function.
In a room with people, the probability that the next (th person) will not have a matching birthday to someone already in the room is:
Hence, the probability that the th person will have a match is:
To compute the expected number of matches in a room of people, we have to calculate:
- the additional matches added by the 1st person plus
- the additional matches added by the 2nd person plus
- the additional matches added by the 3rd person plus
- …
- the additional matches added by the th person plus
- …
- the additional matches added by the th person.
since each additional person will either match or not match, the expected number of additional matches added by the th person is:
So, the number of expected matches for people is:
which simplifies to:
Using the closed form solution for a geometric series, wherein:
Substituting back into the original formula yields:
Notes
The derivation here sheds some light on the applicability of this commonly cited formula.
For instance, it does not count the expected number of unique hits or the expected number of pairings made.
Rather, it counts the number of times that the next person to enter the room has a match.
So, for example, if three people walk in all born on July 1st, the first person does not match (and cannot match), but the second matches and the third matches, for a total of two matches, despite the fact that there is one unique match and three matching pairs.