Lesson 8 of 15
Inclusion-Exclusion & Pigeonhole
Counting Unions and Avoiding Overlaps
Inclusion-Exclusion Principle
When events overlap, naive addition double-counts intersections. The inclusion-exclusion principle corrects this:
Derangements
A derangement is a permutation with no fixed points (no element stays in its original position). The count satisfies:
This follows from inclusion-exclusion applied to the permutations.
Pigeonhole Principle
If objects are placed in bins, at least one bin contains 2 or more objects.
Generalized: If objects go into bins, some bin has at least objects.
def derangements(n):
if n == 0: return 1
if n == 1: return 0
d = [0] * (n + 1)
d[0], d[1] = 1, 0
for i in range(2, n + 1):
d[i] = (i - 1) * (d[i-1] + d[i-2])
return d[n]
print(derangements(4)) # 9
Your Task
Implement inclusion_exclusion_3, derangements, and min_pigeons_for_guarantee.
Pyodide loading...
Loading...
Click "Run" to execute your code.