The Hat Check Problem (Derangements)
Problem
At a party, people each check in their hat. The hats are returned in a completely random order. What is the probability that no one receives their own hat?
Find a closed form, and determine what happens as .
Field
Probability / Combinatorics
Why It's Beautiful
The answer converges to incredibly fast โ for it's already within of . So whether you have 5 people or 5 million, the probability is essentially the same. It's remarkable that a purely combinatorial counting problem produces so naturally.
The key technique โ inclusion-exclusion โ is one of the most versatile tools in combinatorics and probability, and this is its most elegant showcase.
Key Idea / Trick
Let = event that person gets their own hat. You want .
By inclusion-exclusion:
So .
Difficulty
2 / 5
Tags
Probability, Combinatorics, Inclusion-exclusion, Derangements, , Permutations
The Hat Check Problem โ Answer
Setup
A derangement is a permutation of with no fixed points. Let = number of derangements. We want .
Solution via Inclusion-Exclusion
Let = "person gets their own hat." We want .
Step 1. For any set with : since fixing people to their own hats leaves arrangements for the rest.
means the probability of people getting their own hats.
Step 2. By inclusion-exclusion:
The inclusion-exclusion principle expands as:
Grouping by the size of the intersection: there are ways to choose which people all get their own hat, and from Step 1 each such event has probability . So:
The and simplify neatly:
So the sum collapses to:
Step 3. The probability of a derangement is:
This is the partial sum of the Taylor series for at :
Closed Form for
Equivalently, โ the nearest integer to .
Numerical Check
| | | |-----|-------| | 1 | 0 | | 2 | 0.5 | | 3 | 0.333... | | 4 | 0.375 | | 5 | 0.3667 | | 10 | 0.36788... | | | |
The convergence is shockingly fast โ the alternating series error after terms is .
Why This Gives
The Taylor series evaluated at gives exactly . The inclusion-exclusion formula naturally produces the partial sums of this series. The connection is not a coincidence: the Poisson distribution with parameter assigns probability to events โ and a derangement corresponds to zero fixed points when fixed points are approximately Poisson(1).
Bonus: Recursion
with , .
Proof: Person 1 goes to position ( choices). Either person goes to position 1 (giving a derangement of the remaining , so ways), or person does not go to position 1 (equivalent to a derangement of objects, so ways).
Related to Leetcode
This question appeared in the leetcode question 634.Find the Derangement-of-An-Array
See the solution here: solution