Volume 3: Discrete and Probabilistic Mathematics · Part VI: Discrete Mathematics

Chapter 24. Counting and Combinatorics

How many passwords of length 12 are there? How many five-card poker hands? How many ways can a test suite order 10 cases, and how many subsets of 40 features could a model use? Each question asks you to count a set far too large to list. This chapter builds a small toolkit of counting principles (the sum and product rules, permutations, combinations, stars and bars, inclusion–exclusion and the pigeonhole principle) and, just as important, a way of deciding which tool a problem needs. Along the way you will see why brute-forcing a long password is hopeless, why algorithms that try every subset hit a wall, and why no compression program can shrink every file.

Where this chapter sits

You need: multiplication and powers (Chapter 1, Chapter 3), algebraic expansion (Chapter 4, Chapter 7), sets and logic (Chapter 21), and some comfort with proof by induction and by cases (Chapter 22).

This chapter unlocks: probability, where "favourable outcomes over total outcomes" needs exactly these counts (Chapter 29, Chapter 30); graph theory, where you will count edges, paths and spanning trees (Chapter 25); and algorithm analysis in general. The binomial coefficients you meet here reappear in the binomial distribution, in Taylor series (Chapter 14) and in error-correcting codes.

24.1. Why counting needs principles

24.1.1. The problem

"Counting" sounds like the first thing you learned in mathematics. One, two, three. But try these:

  • How many different 4-digit PINs have no repeated digit?

  • How many ways can you choose 6 numbers from 49 in a lottery?

  • How many ways can 7 identical scoops of ice cream be split among 3 flavours?

  • Of the numbers 1 to 1000, how many are divisible by 2, 3 or 5?

You could, in principle, list every case and count. In practice, the lists contain thousands or millions of items, and the classic mistakes are counting something twice or missing a whole family of cases. Combinatorics is the branch of mathematics that counts without listing. Its tools let you reduce "how many?" to a short calculation that you can trust.

24.1.2. Intuition

Every counting technique in this chapter does one of three things:

  1. Break a choice into stages and multiply (the product rule) or into separate cases and add (the sum rule).

  2. Count something easier and correct for over-counting, by dividing (combinations) or subtracting (inclusion–exclusion).

  3. Find a one-to-one correspondence (a bijection) between the thing you want to count and something you already know how to count (stars and bars, subsets as binary strings).

If you remember those three moves, the formulas follow.

Combinatorics, enumeration, outcome

Combinatorics is the mathematics of counting arrangements and selections, and of deciding whether arrangements with given properties exist. To enumerate a set is to list or count its elements. An outcome is one specific result of a choice process (for example, one particular poker hand). For a finite set \(S\), the notation \(|S|\) means the number of elements of \(S\), called its cardinality.

24.2. The sum and product rules

24.2.1. The problem

A café offers 3 mains (pasta, curry, salad) and 2 drinks (tea, water). How many different main-plus-drink meals are there? And if instead you may order either a main or one of 4 desserts (but not both), how many single-item orders are there?

24.2.2. Intuition and the tree diagram

For the meal, imagine making the choice in two stages. First pick a main: 3 branches. From each main, pick a drink: 2 branches. Every complete path from the root to a leaf is one meal, so the number of meals is the number of leaves.

Tree diagram with three main-course branches each splitting into two drink branches
Figure 211. A tree diagram for "a main, then a drink". Each leaf is one outcome; there are 3 × 2 of them.

Each of the 3 first-stage branches sprouts the same number (2) of second-stage branches, so there are \(3 \times 2 = 6\) leaves. That is the product rule.

For "a main or a dessert", there is no sequence of stages, just two disjoint pools of options. You pick from one pool or the other, so there are \(3 + 4 = 7\) options. That is the sum rule.

Sum rule and product rule

Sum rule. If a choice can be made from pool \(A\) or from pool \(B\), and no option is in both (the pools are disjoint, \(A \cap B = \varnothing\)), the number of choices is \(|A| + |B|\).

Product rule. If a process has two stages, the first can be done in \(m\) ways, and for each of those the second can be done in \(n\) ways, the whole process can be done in \(m \times n\) ways. It extends to any number of stages: \(n_1 \times n_2 \times \cdots \times n_k\).

Rule of thumb: "or" between disjoint cases → add; "and then" between stages → multiply.

24.2.3. Why it works

The product rule is really the area of a rectangle. Lay the first-stage options along one side of a grid and the second-stage options along the other. Each cell is one pair, so there are \(m\) rows of \(n\) cells: \(mn\) cells. In set language, the outcomes form the Cartesian product \(A \times B = \{(a, b) : a \in A,\ b \in B\}\), and \(|A \times B| = |A|\,|B|\). With more stages you get a box, or a higher-dimensional box, and the count is still the product of the side lengths.

The important fine print is "for each". The second stage need not offer the same options each time, only the same number of options. When you choose a gold, then a silver medallist from 8 runners, the silver choices depend on who won gold, but there are always 7 of them.

Example 128. Procedure — counting by stages

Input: a description of the objects to count.

Steps:

  1. Describe how to build one object as a sequence of decisions (stages).

  2. Check that every object is produced by exactly one sequence of decisions (no object built twice, none missed).

  3. For each stage, count the options available, given any earlier decisions. Check that this number does not depend on which earlier options were chosen.

  4. Multiply the stage counts. If the objects split into disjoint cases with different stage structures, count each case this way and add.

Output: the number of objects.

24.2.4. Worked example: number plates

A (hypothetical) number plate is 3 letters followed by 4 digits, such as KTX 3071. How many plates are possible? How many if no letter and no digit may repeat? Try it: Count number plates in stages.

Stages: letter 1, letter 2, letter 3, digit 1, …, digit 4. Seven stages.

With repetition allowed, every letter stage has 26 options and every digit stage has 10:

\[\begin{aligned} N &= 26 \times 26 \times 26 \times 10 \times 10 \times 10 \times 10 \\ &= 26^3 \times 10^4 \\ &= 17\,576 \times 10\,000 \\ &= 175\,760\,000. \end{aligned}\]

Without repetition, each stage loses one option for each earlier choice of the same kind: Try it: Plates without repeats.

\[\begin{aligned} N &= (26 \times 25 \times 24) \times (10 \times 9 \times 8 \times 7) \\ &= 15\,600 \times 5\,040 \\ &= 78\,624\,000. \end{aligned}\]

24.2.5. Worked example: the sum rule with cases

How many positive integers less than 1000 have digits that are all odd?

Split by number of digits (disjoint cases, so add):

\[\begin{aligned} \text{1 digit: } & 5 && \text{(1, 3, 5, 7, 9)}\\ \text{2 digits: } & 5 \times 5 = 25 && \text{(product rule per case)}\\ \text{3 digits: } & 5 \times 5 \times 5 = 125\\ \text{total: } & 5 + 25 + 125 = 155. && \text{(sum rule across cases)} \end{aligned}\]

24.2.6. A powerful shortcut: count the complement

How many 4-digit PINs (0000 to 9999) contain at least one repeated digit? "At least one" questions split into many messy cases (exactly one pair, two pairs, a triple …). Instead, count what you don’t want and subtract from the total: Try it: PINs with no repeated digit.

\[\begin{aligned} \text{all PINs} &= 10^4 = 10\,000\\ \text{PINs with no repeat} &= 10 \times 9 \times 8 \times 7 = 5\,040\\ \text{PINs with some repeat} &= 10\,000 - 5\,040 = 4\,960. \end{aligned}\]

Almost half of all PINs repeat a digit. Counting the complement is the single most useful trick in elementary counting, and it is exactly the move behind the birthday paradox later in this chapter.

Adding overlapping cases; multiplying dependent stages
  • The sum rule needs disjoint cases. "How many cards are red or a king?" is not \(26 + 4 = 30\): the two red kings were counted twice. The correct count is \(26 + 4 - 2 = 28\). Fixing this properly is the job of inclusion–exclusion (Section 24.9).

  • The product rule needs a constant number of options per stage. "Choose a card, then a second card of the same suit" works (always 12 options), but "choose a number from 1–10, then a larger number" does not: the second stage has 9 options after choosing 1 but 0 after choosing 10. Split into cases instead.

  • Each object must be built by exactly one sequence of choices. If you count two-person teams by "pick the first person, then the second", the team {Ann, Bob} is built twice. That over-count is the whole story of combinations (Section 24.4).

Computer-science connection: nested loops are the product rule

A loop nest is a product rule you can execute:

mains = ["pasta", "curry", "salad"]
drinks = ["tea", "water"]
for main in mains:          # 3 iterations
    for drink in drinks:    # 2 iterations each
        print(main, drink)  # runs 3 * 2 = 6 times

This is the root of complexity analysis. Two nested loops over \(n\) items do \(n^2\) units of work; \(k\) nested loops do \(n^k\). Python’s itertools.product(mains, drinks) is the Cartesian product \(A \times B\) packaged as an iterator. Configuration spaces (every combination of OS × browser × locale for a test matrix) grow multiplicatively for the same reason: 4 operating systems × 5 browsers × 30 locales is already 600 test configurations.

24.2.7. Where you’d use this

Biology: why the genetic code uses triplets. DNA has 4 bases and must encode 20 amino acids. Words of 2 bases give only \(4^2 = 16\) possibilities, too few; words of 3 give \(4^3 = 64\), enough with room to spare. The product rule predicts the three-letter codon, and the spare capacity shows up as redundancy: most amino acids have several codons.

Engineering: test matrices. A web app that must work on 3 browsers, 4 operating systems and 2 languages has \(3 \times 4 \times 2 = 24\) configurations. Add 5 screen sizes and it is 120. Product-rule growth is why testers use pairwise testing, which covers every pair of settings with far fewer runs.

Everyday. A combination bike lock with 4 dials of 10 digits has \(10^4 = 10\,000\) settings; at one try every 2 seconds, trying them all takes under 6 hours. A 3-dial lock (1,000 settings) falls in about half an hour.

US curriculum

The Fundamental Counting Principle (the product rule) and tree diagrams appear in Grade 7 probability (compound events) and again in Algebra II or Precalculus. The phrase "Fundamental Counting Principle" is what a US student will recognise.

24.3. Permutations: arranging things in order

24.3.1. The problem

Eight runners contest a race. In how many ways can gold, silver and bronze be awarded? In how many ways can all eight finish, in order?

24.3.2. Intuition

Fill the podium one step at a time. Any of the 8 runners can win gold. Whoever wins, 7 remain for silver, then 6 for bronze. The product rule gives \(8 \times 7 \times 6 = 336\). For a complete finishing order, keep going all the way down: \(8 \times 7 \times 6 \times 5 \times 4 \times 3 \times 2 \times 1\).

Factorial

For a positive integer \(n\), n factorial, written \(n!\), is the product of all integers from \(1\) to \(n\): \(n! = n \times (n-1) \times \cdots \times 2 \times 1\). So \(3! = 6\), \(5! = 120\), \(10! = 3\,628\,800\). By convention \(0! = 1\).

\(n!\) counts the ways to arrange \(n\) distinct objects in a row. The useful identity \(n! = n \times (n-1)!\) is the recursive definition you would write in code.

Permutation and r-permutation

A permutation of a set is an arrangement of all its elements in an order. An \(r\)-permutation of \(n\) distinct objects is an ordered selection of \(r\) of them (no repeats). The number of \(r\)-permutations is written \(P(n, r)\), \({}_nP_r\) or \(n^{\underline{r}}\) (read "\(n\) to the \(r\) falling"):

\[P(n, r) = n (n-1)(n-2)\cdots(n-r+1) = \frac{n!}{(n-r)!}.\]

24.3.3. Why it works: deriving \(P(n, r)\)

There are \(r\) stages. Stage 1 has \(n\) options. Each earlier stage has used up one object, so stage \(i\) has \(n - (i-1)\) options. The last stage, stage \(r\), has \(n - r + 1\). By the product rule,

\[P(n, r) = \underbrace{n (n-1) \cdots (n-r+1)}_{r \text{ factors}}.\]

To see the factorial form, multiply and divide by the "missing tail" \((n-r)!\):

\[\begin{aligned} P(n, r) &= n (n-1)\cdots(n-r+1) \cdot \frac{(n-r)(n-r-1)\cdots 1}{(n-r)(n-r-1)\cdots 1}\\ &= \frac{n!}{(n-r)!}. \end{aligned}\]

The product form is better for hand calculation (\(P(8, 3) = 8 \cdot 7 \cdot 6\) is immediate, while \(8!/5!\) invites you to compute two large numbers and divide). The factorial form is better for algebra.

24.3.4. Why \(0! = 1\)

With \(r = n\), the formula says \(P(n, n) = n!/0!\). But \(P(n, n)\) is the number of orderings of all \(n\) objects, which is \(n!\). So \(0!\) has to be \(1\) for the formula to work. There is also a direct reason: there is exactly one way to arrange nothing (the empty arrangement). And the recursion \(n! = n \cdot (n-1)!\) at \(n = 1\) gives \(1 = 1 \cdot 0!\). Three different arguments, one answer: this is a definition chosen because it makes everything consistent, not an arbitrary rule.

24.3.5. Worked examples

Podium. \(P(8, 3) = 8 \times 7 \times 6 = 336\).

Full finishing order. \(8! = 40\,320\).

Seating with a constraint. Five people, including Ann and Bob, sit in a row. In how many arrangements are Ann and Bob next to each other?

Glue Ann and Bob into a single block. Now arrange 4 units (the block and three others), then arrange the two people inside the block:

\[\begin{aligned} \text{arrange 4 units} &: 4! = 24\\ \text{order inside block} &: 2! = 2\\ \text{total} &: 24 \times 2 = 48. \end{aligned}\]

As a check, the arrangements where they are not adjacent number \(5! - 48 = 120 - 48 = 72\).

Round table. In how many ways can 5 people sit round a circular table, if only who sits next to whom matters (rotations are the same seating)? Each circular seating corresponds to 5 different linear ones (start reading at any of the 5 seats), so the count is \(5!/5 = 4! = 24\). In general, \((n-1)!\) circular arrangements. This is your first glimpse of "count something easier, then divide out the over-count". Try it: Round-table seatings counted five times.

Permutations in the wild

A standard deck has \(52! \approx 8.07 \times 10^{67}\) orderings. That is so large that every thoroughly shuffled deck in history has almost certainly been in an order never seen before. If every person on Earth had shuffled a deck once a second since the Big Bang, the total number of shuffles would be roughly \(3 \times 10^{27}\), a fraction of about \(4 \times 10^{-41}\) of the possible orders.

Computer-science connection: sorting and n!

A comparison sort must distinguish all \(n!\) possible input orders, and each comparison has two outcomes. A decision tree with \(n!\) leaves needs depth at least \(\log_2(n!)\), and \(\log_2(n!) \approx n \log_2 n\) (see Chapter 12). That is the counting argument behind the \(O(n \log n)\) lower bound for comparison sorting: no amount of cleverness can beat it.

24.3.6. Where you’d use this

Sport. With 8 sprinters in a final, the number of possible podiums (gold, silver, bronze) is \(P(8, 3) = 8 \cdot 7 \cdot 6 = 336\). Order matters, so it is a permutation; the number of possible sets of medallists is only \(336 / 3! = 56\).

Logistics. A delivery driver with 10 drops can visit them in \(10! = 3\,628\,800\) orders. With 20 drops it is about \(2.4 \times 10^{18}\), which is why route planners use heuristics instead of checking every order (the travelling salesman problem, Chapter 25).

History of cryptography. The German Army’s Enigma machine placed 3 of its 5 rotors into 3 slots, and order mattered: \(P(5, 3) = 60\) wheel orders. Each of the 60 had to be tested separately, which is one reason the Bletchley Park codebreakers built banks of electromechanical "bombes" to run in parallel.

24.4. Combinations: choosing when order doesn’t matter

24.4.1. The problem

A club of 10 people must choose a committee of 3. How many different committees are possible?

24.4.2. Intuition: count ordered, then divide

You already know how to count ordered choices: \(P(10, 3) = 10 \cdot 9 \cdot 8 = 720\). But a committee is a set of people; {Ann, Bob, Cat} is the same committee however you list them. Each committee shows up in the ordered count once for each of its orderings, and three people can be ordered in \(3! = 6\) ways: Try it: Each committee counted 3! times.

ordered lists that all describe the committee {A, B, C}:
  ABC  ACB  BAC  BCA  CAB  CBA      (3! = 6 of them)

Every committee is counted exactly 6 times, so the number of committees is \(720 / 6 = 120\).

Combination and binomial coefficient

A combination (or \(r\)-combination) of \(n\) distinct objects is an unordered selection of \(r\) of them, that is, a subset of size \(r\). The number of them is the binomial coefficient

\[\binom{n}{r} = \frac{n!}{r!\,(n-r)!},\]

read "\(n\) choose \(r\)". Other notations: \(C(n, r)\), \({}_nC_r\), \({}^nC_r\) (common in UK textbooks). By convention \(\binom{n}{r} = 0\) if \(r < 0\) or \(r > n\).

24.4.3. Why it works: the division principle

Here is the derivation made precise. Consider all ordered selections of \(r\) objects from \(n\). Build each one in two stages:

  1. choose which \(r\) objects (a combination): \(\binom{n}{r}\) ways;

  2. choose the order of those \(r\) objects: \(r!\) ways.

Every ordered selection arises exactly once this way, so by the product rule

\[\begin{aligned} P(n, r) &= \binom{n}{r} \cdot r! \\[4pt] \binom{n}{r} &= \frac{P(n, r)}{r!} = \frac{n!}{(n-r)!\,r!}. \end{aligned}\]

This is the division principle: if a count treats every object you care about exactly \(k\) times, divide by \(k\).

For hand calculation, use the cancelled form: \(\binom{n}{r} = \dfrac{n (n-1) \cdots (n-r+1)}{r!}\), with \(r\) factors on top and \(r!\) below.

24.4.4. Symmetry

Choosing the 3 people who are on the committee is the same as choosing the 7 who are not. So

\[\binom{n}{r} = \binom{n}{n-r}.\]

The formula confirms it (swap \(r\) and \(n-r\) in the denominator), but the counting argument says why. It also saves work: \(\binom{100}{98} = \binom{100}{2} = \dfrac{100 \cdot 99}{2} = 4950\).

24.4.5. Worked example: committees with structure

From 10 people (4 women and 6 men), how many 4-person committees have exactly 2 women?

Stage 1, choose the women; stage 2, choose the men. These are independent, so multiply:

\[\begin{aligned} \binom{4}{2} \binom{6}{2} &= \frac{4 \cdot 3}{2 \cdot 1} \cdot \frac{6 \cdot 5}{2 \cdot 1}\\ &= 6 \times 15 \\ &= 90. \end{aligned}\]

How many have at least one woman? Use the complement:

\[\begin{aligned} \text{all committees} &= \binom{10}{4} = \frac{10 \cdot 9 \cdot 8 \cdot 7}{4 \cdot 3 \cdot 2 \cdot 1} = \frac{5040}{24} = 210\\ \text{no women} &= \binom{6}{4} = \binom{6}{2} = 15\\ \text{at least one woman} &= 210 - 15 = 195. \end{aligned}\]

24.4.6. Worked example: a committee with a chair

Choose a 3-person committee from 10 and name one of the three as chair. Two methods: Try it: Committee with a chair, both ways.

  • Committee first. \(\binom{10}{3} = 120\) committees, then 3 choices of chair: \(120 \times 3 = 360\).

  • Chair first. 10 choices of chair, then choose the other 2 from the remaining 9: \(10 \times \binom{9}{2} = 10 \times 36 = 360\).

Both agree, which is the point. When you can count the same set two ways, you have not just a check but an identity: \(3\binom{10}{3} = 10\binom{9}{2}\), and in general \(r\binom{n}{r} = n\binom{n-1}{r-1}\). Proofs of this kind, called double counting or combinatorial proofs, are the subject’s favourite technique, and you will use one next for Pascal’s rule.

Forgetting whether order matters

The most common counting error is using \(P\) where \(C\) belongs or the reverse. Ask: if I swapped two of the chosen items, would I have a different outcome? Swapping two committee members gives the same committee (use \(C\)). Swapping the gold and silver medallists gives a different podium (use \(P\)). Swapping two digits of a PIN gives a different PIN (order matters, and repetition is allowed: \(n^r\), see Section 24.11).

A second trap: mixing ordered and unordered stages. "Choose 2 women, then 2 men" is fine. But "choose one woman to guarantee at least one, then choose 3 more from the other 9" gives \(4 \times \binom{9}{3} = 336\), not 195, because a committee with two women is built twice (once for each woman as "the guaranteed one"). When an answer to an "at least" question comes out too big, suspect this.

Computer-science connection: math.comb and itertools

Python’s standard library knows all of this:

import math

def perm(n, r):
    """Ordered selections of r from n distinct items: n!/(n-r)!"""
    return math.factorial(n) // math.factorial(n - r)

def comb(n, r):
    """Unordered selections: divide out the r! orderings of each selection."""
    return perm(n, r) // math.factorial(r)

print(perm(10, 3), math.perm(10, 3))
print(comb(10, 3), math.comb(10, 3))
print(math.comb(52, 5))
print(math.comb(49, 6))
720 720
120 120
2598960
13983816

math.comb and math.perm (Python 3.8+) use exact integer arithmetic, so they never overflow. When you need the objects themselves rather than the count, itertools generates them lazily:

from itertools import permutations, combinations, product, combinations_with_replacement

letters = "ABC"
print(list(permutations(letters, 2)))
print(list(combinations(letters, 2)))
print(list(product(letters, repeat=2)))
print(list(combinations_with_replacement(letters, 2)))
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
[('A', 'B'), ('A', 'C'), ('B', 'C')]
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]

The four lines have 6, 3, 9 and 6 items: \(P(3,2)\), \(\binom{3}{2}\), \(3^2\) and \(\binom{4}{2}\). Those are exactly the four cells of the decision table in Section 24.11.

24.4.7. Where you’d use this

Sport. A 20-team league in which every pair of teams meets twice (home and away) plays \(2\binom{20}{2} = 380\) matches, which is exactly the length of an English Premier League season.

Engineering: links in a network. Connecting every pair of 50 offices directly needs \(\binom{50}{2} = 1225\) links; routing everything through one hub needs 49. That quadratic-versus-linear gap is why telephone exchanges, Ethernet switches and airline hubs exist.

Science: screening combinations. A lab with 20 candidate drugs that wants to test every pair needs \(\binom{20}{2} = 190\) experiments; every triple needs \(\binom{20}{3} = 1140\). Counting first tells you whether an exhaustive screen is affordable or whether you need a statistical design that samples combinations.

Everyday. Choosing 3 pizza toppings from 12 gives \(\binom{12}{3} = 220\) different pizzas, and the menu that boasts "over 200 combinations" is quoting exactly this number.

US curriculum

Permutations and combinations (usually written \({}_nP_r\) and \({}_nC_r\), and computed on a TI-84 graphing calculator) appear in Algebra II and Precalculus, and heavily in AP Statistics as preparation for probability. Combinatorial proof and double counting are usually first met in a college Discrete Mathematics course or in competition preparation (AMC 10/12).

24.5. Binomial coefficients and Pascal’s triangle

24.5.1. The problem

Computing \(\binom{n}{r}\) from factorials is fine for a calculator, but it hides a beautiful structure. Is there a way to build all the binomial coefficients from simpler ones, without any multiplication or division?

24.5.2. Pascal’s triangle

Write \(\binom{n}{0}, \binom{n}{1}, \ldots, \binom{n}{n}\) as row \(n\) of a triangle, rows centred:

Pascal’s triangle with rows 0 to 8, highlighting 10 plus 10 equals 20
Figure 212. Pascal’s triangle, rows 0 to 8. Each entry is the sum of the two entries above it.

Each row begins and ends with 1, and every interior entry is the sum of the two diagonally above it. In symbols, that is Pascal’s rule. Try it: Explore Pascal’s triangle.

24.5.3. Pascal’s rule and its counting proof

\[\binom{n}{r} = \binom{n-1}{r-1} + \binom{n-1}{r} \qquad (1 \le r \le n-1).\]

You could prove this by adding fractions of factorials. The counting proof is shorter and tells you why.

Proof. Count the \(r\)-element subsets of a set of \(n\) people, one of whom is called Zoe. The left side, \(\binom{n}{r}\), counts all of them directly. Now sort the subsets into two disjoint cases:

  • Subsets containing Zoe. Zoe is in; choose the other \(r-1\) members from the remaining \(n-1\) people: \(\binom{n-1}{r-1}\) ways.

  • Subsets not containing Zoe. Choose all \(r\) members from the other \(n-1\) people: \(\binom{n-1}{r}\) ways.

Every subset is in exactly one case, so by the sum rule the total is \(\binom{n-1}{r-1} + \binom{n-1}{r}\). Both sides count the same set, so they are equal. \(\blacksquare\)

This "single out one element and ask whether it’s in" move is also the recursion behind many algorithms (the 0/1 knapsack dynamic programme makes exactly this decision for each item).

24.5.4. More patterns in the triangle

  • Row sums are powers of 2: \(\binom{n}{0} + \binom{n}{1} + \cdots + \binom{n}{n} = 2^n\). Counting proof: the left side counts subsets of an \(n\)-element set by size; the right side counts them by deciding, for each element, "in or out", \(2\) ways each, \(n\) times.

  • Symmetry \(\binom{n}{r} = \binom{n}{n-r}\) is the left–right mirror symmetry.

  • The hockey stick. Summing down a diagonal gives the entry just below and to the side: \(\binom{2}{2} + \binom{3}{2} + \binom{4}{2} + \binom{5}{2} = 1 + 3 + 6 + 10 = 20 = \binom{6}{3}\). Try it: Highlight the hockey stick.

  • Diagonals: the second diagonal (1, 2, 3, 4, …) is the counting numbers; the third (1, 3, 6, 10, 15, …) is the triangular numbers \(\binom{n}{2} = n(n-1)/2\), the number of handshakes among \(n\) people or the number of pairs to compare in a naive all-pairs algorithm.

Example 129. Procedure — computing binomial coefficients

Input: non-negative integers \(n\) and \(r \le n\).

Steps:

  1. If \(r > n - r\), replace \(r\) by \(n - r\) (symmetry; fewer factors).

  2. Set \(c = 1\).

  3. For \(i = 1, 2, \ldots, r\): set \(c \leftarrow c \cdot (n - r + i) / i\). (After step \(i\), \(c = \binom{n-r+i}{i}\), which is an integer, so the division is always exact.)

Output: \(c = \binom{n}{r}\).

For example, \(\binom{8}{3}\): \(c = 1 \cdot 6/1 = 6\), then \(6 \cdot 7/2 = 21\), then \(21 \cdot 8/3 = 56\). The intermediate values 6, 21, 56 are themselves binomial coefficients (\(\binom{6}{1}, \binom{7}{2}, \binom{8}{3}\)). If instead you need a whole table, build Pascal’s triangle by addition, which is what a dynamic-programming solution does.

Not Pascal’s triangle

The triangle is named after Blaise Pascal’s 1654 treatise, but it was known centuries earlier: to Jia Xian in 11th-century China (it is called Yang Hui’s triangle in China after the 13th-century mathematician who popularised it), to Omar Khayyam in Persia (Khayyam’s triangle in Iran), and in India, where Pingala’s work on poetic metres (c. 200 BCE) implicitly counted combinations. Colour the odd entries black and the even ones white, and Sierpiński’s fractal triangle appears.

Pascal’s triangle explorer

Display Pascal’s triangle up to row 64. Let the reader colour entries by their remainder modulo 2, 3 or 5, and watch fractal patterns emerge. Clicking an entry highlights the two entries that sum to it, the hockey-stick diagonal ending at it, and its value as \(n!/(r!(n-r)!)\).

24.6. The binomial theorem

24.6.1. The problem

Expand \((x + y)^5\) without multiplying out five brackets by hand. More generally, what is the coefficient of \(x^3 y^2\) in \((x+y)^5\), and why are binomial coefficients called binomial?

24.6.2. Intuition: expansion is a counting process

Write \((x+y)^3 = (x + y)(x + y)(x + y)\). Fully expanding means: from each of the three brackets pick either \(x\) or \(y\), multiply your three picks, and add up the results over all \(2^3 = 8\) ways of picking:

xxx  xxy  xyx  xyy  yxx  yxy  yyx  yyy

The term \(x^2 y\) appears once for each way of choosing which one bracket supplies the \(y\): \(\binom{3}{1} = 3\) ways (xxy, xyx, yxx). So

\[(x + y)^3 = \binom{3}{0}x^3 + \binom{3}{1}x^2y + \binom{3}{2}xy^2 + \binom{3}{3}y^3 = x^3 + 3x^2y + 3xy^2 + y^3.\]

The coefficients 1, 3, 3, 1 are row 3 of Pascal’s triangle. That is why they’re called binomial coefficients: they are the coefficients in the expansion of a power of a binomial (a two-term expression).

Binomial, the Σ notation

A binomial is a polynomial with two terms, such as \(x + y\) or \(2x - 1\).

The summation sign \(\sum\) (capital Greek sigma, for "sum") packages a long sum. \(\sum_{k=0}^{n} a_k\) means "let the index \(k\) run through the integers from the lower limit \(0\) to the upper limit \(n\), and add up the terms \(a_k\)": \(a_0 + a_1 + \cdots + a_n\).

24.6.3. The theorem

For any numbers \(x, y\) and non-negative integer \(n\),

\[(x + y)^n = \sum_{k=0}^{n} \binom{n}{k} x^{n-k} y^k.\]

Why. Each term of the expansion comes from choosing \(x\) or \(y\) from each of the \(n\) brackets. A choice that takes \(y\) from exactly \(k\) brackets (and so \(x\) from the other \(n-k\)) contributes \(x^{n-k} y^k\). The number of such choices is the number of ways to pick which \(k\) brackets supply \(y\), namely \(\binom{n}{k}\). Collect like terms and you get the theorem. (A proof by induction using Pascal’s rule also works; see Chapter 22. The counting proof is the one that explains it.)

Example 130. Procedure — expanding \((a + b)^n\)

Input: the two terms \(a\), \(b\) (each may include a coefficient and a sign), and \(n\).

Steps:

  1. Write row \(n\) of Pascal’s triangle: \(\binom{n}{0}, \ldots, \binom{n}{n}\).

  2. For \(k = 0, \ldots, n\), form the term \(\binom{n}{k}\, a^{n-k}\, b^{k}\): powers of \(a\) count down from \(n\), powers of \(b\) count up from 0.

  3. Simplify each term, keeping track of the signs and coefficients inside \(a\) and \(b\).

Output: the expanded polynomial, with \(n + 1\) terms.

24.6.4. Worked example: \((x + 2)^4\)

Here \(a = x\), \(b = 2\), \(n = 4\); row 4 is 1, 4, 6, 4, 1. Try it: Expand (x + 2)⁴.

\[\begin{aligned} (x + 2)^4 &= 1 \cdot x^4 \cdot 2^0 + 4 \cdot x^3 \cdot 2^1 + 6 \cdot x^2 \cdot 2^2 + 4 \cdot x \cdot 2^3 + 1 \cdot x^0 \cdot 2^4\\ &= x^4 + 4 \cdot 2\, x^3 + 6 \cdot 4\, x^2 + 4 \cdot 8\, x + 16\\ &= x^4 + 8x^3 + 24x^2 + 32x + 16. \end{aligned}\]

Check by substituting \(x = 1\): the left side is \(3^4 = 81\); the right side is \(1 + 8 + 24 + 32 + 16 = 81\). Substituting a convenient value is a quick, reliable test of any expansion.

24.6.5. Worked example: a single coefficient

Find the coefficient of \(x^3\) in \((2x - 1)^5\). You do not need the whole expansion. Here \(a = 2x\), \(b = -1\), \(n = 5\). A term has the form \(\binom{5}{k}(2x)^{5-k}(-1)^k\), which contains \(x^{5-k}\). For \(x^3\) you need \(5 - k = 3\), so \(k = 2\): Try it: Find the x³ coefficient.

\[\begin{aligned} \binom{5}{2}(2x)^3(-1)^2 &= 10 \cdot 8x^3 \cdot 1\\ &= 80x^3. \end{aligned}\]

The coefficient is \(80\).

24.6.6. Consequences you get for free

  • Put \(x = y = 1\): \(2^n = \sum_k \binom{n}{k}\), the row-sum identity again.

  • Put \(x = 1, y = -1\): \(0 = \binom{n}{0} - \binom{n}{1} + \binom{n}{2} - \cdots\) for \(n \ge 1\). A set has as many even-sized subsets as odd-sized ones.

  • For small \(y\), \((1 + y)^n \approx 1 + ny + \binom{n}{2}y^2\). With \(y = 0.05\) and \(n = 10\), compound growth \(1.05^{10} \approx 1 + 0.5 + 45 \times 0.0025 = 1.6125\); the true value is \(1.6289\). This truncated expansion is the seed of Taylor series (Chapter 14).

Dropping the coefficients inside the terms

In \((2x - 1)^5\), the term is \(\binom{5}{k}(2x)^{5-k}(-1)^k\), not \(\binom{5}{k}\,2x^{5-k}\ldots\). The 2 is raised to the power too, and so is the minus sign. Bracket each of \(a\) and \(b\) before raising them to powers, and the signs take care of themselves (they alternate when \(b\) is negative).

Computer-science connection: binomial coefficients at work
  • Probability. The probability of exactly \(k\) heads in \(n\) tosses of a coin with heads-probability \(p\) is \(\binom{n}{k}p^k(1-p)^{n-k}\), one term of \((p + (1-p))^n = 1\). This is the binomial distribution (Chapter 30).

  • Error-correcting codes. The number of bit strings of length \(n\) within Hamming distance \(t\) of a codeword is \(\sum_{k=0}^{t}\binom{n}{k}\), which bounds how many codewords can fit (the Hamming bound).

  • Big-number arithmetic. \((a + b)^p \equiv a^p + b^p \pmod p\) for a prime \(p\), because every middle coefficient \(\binom{p}{k}\) is divisible by \(p\). This "freshman’s dream" underlies Fermat’s little theorem and primality tests (Chapter 23).

24.6.7. Where you’d use this

Genetics: how likely is "exactly one"? Two parents who both carry a recessive gene each pass it on with probability \(\tfrac12\), so each child is affected with probability \(\tfrac14\). In a family of 4 children, the chance that exactly one is affected is one term of the binomial expansion of \((\tfrac14 + \tfrac34)^4\): Try it: Exactly one of four children.

\[\binom{4}{1}\left(\tfrac14\right)^1\left(\tfrac34\right)^3 = 4 \cdot \frac{1}{4} \cdot \frac{27}{64} = \frac{27}{64} \approx 0.42.\]

The coefficient 4 counts which child it is; the powers give the probability of one particular pattern. Chapter 30 turns this into the binomial distribution.

Finance and physics: quick approximations. The truncated expansion above, \((1 + y)^n \approx 1 + ny\), is how people estimate small compound changes in their heads (2% a year for 5 years is roughly 10%; the exact figure is 10.4%), and how physicists simplify formulas such as \((1 - v^2/c^2)^{-1/2} \approx 1 + \tfrac12 v^2/c^2\) at everyday speeds (the binomial series for non-integer powers, Chapter 14).

US curriculum

The binomial theorem and its link to Pascal’s triangle are taught in Algebra II or Precalculus (Common Core standard A-APR.C.5). Sigma notation is usually introduced alongside sequences and series in Precalculus.

24.7. Repetition: words, multisets and anagrams

24.7.1. The problem

How many 4-letter "words" (any strings, not necessarily English) use the letters A–Z? How many distinct rearrangements are there of the letters of MISSISSIPPI?

24.7.2. Ordered selection with repetition

When repetition is allowed and order matters, each of the \(r\) positions independently has \(n\) options:

\[\underbrace{n \times n \times \cdots \times n}_{r \text{ times}} = n^r.\]

So there are \(26^4 = 456\,976\) four-letter strings, \(10^4\) four-digit PINs, and \(2^n\) bit strings of length \(n\). This is the count behind every keyspace calculation in security.

24.7.3. Arrangements of a multiset

MISSISSIPPI has 11 letters, but they are not all distinct: M once, I four times, S four times, P twice. If the letters were all different (label them \(I_1, I_2, I_3, I_4\) and so on), there would be \(11!\) arrangements. But swapping the labelled I’s among themselves gives the same word; each word is counted \(4!\) times on account of the I’s, and likewise \(4!\) for the S’s and \(2!\) for the P’s. Divide out each over-count: Try it: Step through MISSISSIPPI anagrams.

\[\begin{aligned} \frac{11!}{1!\,4!\,4!\,2!} &= \frac{39\,916\,800}{1 \cdot 24 \cdot 24 \cdot 2}\\ &= \frac{39\,916\,800}{1152}\\ &= 34\,650. \end{aligned}\]
Multiset and multinomial coefficient

A multiset is like a set but elements may appear more than once: \(\{M, I, I, I, I, S, S, S, S, P, P\}\). The number of distinct orderings of a multiset with \(n\) items, of which \(n_1\) are of type 1, \(n_2\) of type 2, …, \(n_k\) of type \(k\), is the multinomial coefficient

\[\binom{n}{n_1, n_2, \ldots, n_k} = \frac{n!}{n_1!\,n_2!\cdots n_k!}, \qquad n_1 + \cdots + n_k = n.\]

With two types it is just \(\binom{n}{n_1}\): arranging \(r\) identical H’s and \(n-r\) identical T’s is choosing which \(r\) positions get an H.

Another way to see it. Place the letters into 11 slots in stages: choose 1 slot for M, then 4 of the remaining 10 for the I’s, then 4 of the remaining 6 for the S’s, and the last 2 go to the P’s:

\[\binom{11}{1}\binom{10}{4}\binom{6}{4}\binom{2}{2} = 11 \times 210 \times 15 \times 1 = 34\,650.\]

Same answer, by a method that never divides. Both are worth having: the first is faster to write, the second is easier to justify step by step.

Grid paths. How many shortest routes are there on a city grid from one corner to a point 5 blocks east and 3 blocks north? Every shortest route is a string of 5 E’s and 3 N’s in some order, so the count is \(\binom{8}{3} = 56\). Recognising a problem as "arrangements of a multiset" in disguise is a recurring skill. Try it: Walk the 56 grid routes.

24.8. Stars and bars: distributing identical objects

24.8.1. The problem

An ice-cream shop has 3 flavours: vanilla, chocolate and mint. You order a tub of 7 scoops. Scoops of the same flavour are identical, and only how many of each flavour you get matters. How many different tubs are there?

In algebraic form: how many solutions are there to

\[x_1 + x_2 + x_3 = 7, \qquad x_i \text{ non-negative integers}?\]

24.8.2. Intuition: a bijection with strings

Draw each scoop as a star \(\star\) and separate the flavours with 2 bars:

Stars and bars diagrams for distributing 7 scoops among 3 flavours
Figure 213. Two tubs of 7 scoops encoded as stars and bars. Every arrangement of 7 stars and 2 bars is a different tub, and vice versa.

Stars before the first bar are vanilla, between the bars chocolate, after the second bar mint. Two bars together (||*) means zero chocolate. Every tub gives exactly one such string, and every string of 7 stars and 2 bars gives exactly one tub. So count the strings: 9 positions, choose which 2 hold bars: \(\binom{9}{2} = 36\). Try it: Drag the stars and bars.

24.8.3. The general formula

Distributing \(n\) identical objects into \(k\) distinct boxes (empty boxes allowed) uses \(n\) stars and \(k - 1\) bars, so

\[\#\text{ways} = \binom{n + k - 1}{k - 1} = \binom{n + k - 1}{n}.\]

Equivalently, this is the number of multisets of size \(n\) drawn from \(k\) types: unordered selection with repetition. That fills the last cell of the order/repetition table.

24.8.4. Worked example: at least one of each

How many tubs of 7 scoops have at least one scoop of each flavour (\(x_i \ge 1\))? Try it: At least one of each.

Hand out one scoop of each flavour first. That leaves 4 scoops to distribute freely among 3 flavours: \(y_1 + y_2 + y_3 = 4\) with \(y_i = x_i - 1 \ge 0\):

\[\binom{4 + 3 - 1}{3 - 1} = \binom{6}{2} = 15.\]

Alternatively, think of the 7 stars in a row with 6 gaps between them; placing 2 bars in 2 different gaps (no empty flavour) is \(\binom{6}{2} = 15\).

24.8.5. Worked example: a dozen doughnuts

A shop sells 5 kinds of doughnut. How many different boxes of 12 can you buy? Here \(n = 12\) objects into \(k = 5\) kinds: Try it: List the 1820 doughnut boxes.

\[\binom{12 + 5 - 1}{5 - 1} = \binom{16}{4} = \frac{16 \cdot 15 \cdot 14 \cdot 13}{4 \cdot 3 \cdot 2 \cdot 1} = \frac{43\,680}{24} = 1820.\]
Example 131. Procedure — distributing identical objects

Input: \(n\) identical objects, \(k\) distinct boxes, lower bounds \(m_1, \ldots, m_k\) (use 0 if none).

Steps:

  1. Pre-load each box \(i\) with its minimum \(m_i\). Set \(n' = n - (m_1 + \cdots + m_k)\). If \(n' < 0\), the answer is 0.

  2. Distribute the remaining \(n'\) objects freely: \(\binom{n' + k - 1}{k - 1}\).

  3. If there are also upper bounds, count the solutions that violate them and remove those with inclusion–exclusion (Section 24.9).

Output: the number of distributions.

Distinct objects are a different problem

Stars and bars needs identical objects. Seven different people choosing among 3 rooms is \(3^7 = 2187\) (each person independently picks a room), not \(\binom{9}{2}\). Ask: if I swapped two of the objects, would the outcome change? If yes, they are distinct and you want the product rule.

Computer-science connection: stars and bars in the wild

Stars and bars counts the monomials of degree \(n\) in \(k\) variables (\(x^2y^3z^2\) is "7 scoops: 2 of x, 3 of y, 2 of z"), so it tells you how many features a degree-\(d\) polynomial model creates; for 10 input features and degree 3, there are \(\binom{12}{3} = 220\) monomials of degree exactly 3. It also counts ways to split a budget of \(n\) identical units (CPU shares, replicas) among \(k\) services, the size of the search space for such allocation problems.

24.8.6. Where you’d use this

Physics: counting microstates. In the simplest model of a solid (Einstein’s), energy comes in identical packets, quanta, shared among atomic oscillators. The number of ways to share \(q\) quanta among \(N\) oscillators is a stars-and-bars count, \(\binom{q + N - 1}{q}\). Three quanta among three oscillators: \(\binom{5}{3} = 10\) microstates (3-0-0 in 3 ways, 2-1-0 in 6 ways, 1-1-1 in 1 way). Statistical mechanics defines entropy from exactly this count, and it is why heat flows from hot to cold: that direction has overwhelmingly more microstates.

Everyday. Splitting $10 of pocket money, in whole dollars, between saving, spending and giving: \(\binom{12}{2} = 66\) possible plans. Allocating 6 identical seats among 3 parties: \(\binom{8}{2} = 28\) possible results.

Stars and bars sliders

Choose \(n\) (scoops) and \(k\) (flavours). The lab shows a random distribution as stars and bars and as a vector \((x_1, \ldots, x_k)\); dragging a bar moves stars between flavours. A counter enumerates all distributions for small \(n, k\) and confirms the formula \(\binom{n+k-1}{k-1}\).

24.9. Inclusion–exclusion

24.9.1. The problem

Of the integers from 1 to 1000, how many are divisible by 2, by 3 or by 5?

24.9.2. Intuition: correct the double counting

For two sets, adding \(|A| + |B|\) counts the overlap twice, so subtract it once:

\[|A \cup B| = |A| + |B| - |A \cap B|.\]

For three sets, adding the three sizes counts each two-way overlap twice and the triple overlap three times. Subtracting the three pairwise intersections fixes the two-way regions, but now the triple region has been added 3 times and subtracted 3 times, so it isn’t counted at all. Add it back once:

\[|A \cup B \cup C| = |A| + |B| + |C| - |A \cap B| - |A \cap C| - |B \cap C| + |A \cap B \cap C|.\]
Venn diagrams for two and three sets showing how each region is counted
Figure 214. Inclusion–exclusion for two and three sets: the bookkeeping in each region of the Venn diagram.
Union, intersection, Venn diagram

The union \(A \cup B\) is the set of elements in \(A\) or \(B\) (or both). The intersection \(A \cap B\) is the set of elements in both. A Venn diagram draws sets as overlapping regions so that each region represents one combination of "in" and "out". See Chapter 21 for the full set vocabulary.

24.9.3. Why it works in general

For \(k\) sets the pattern continues: add the single sets, subtract all pairwise intersections, add all triple intersections, subtract quadruples, and so on, with alternating signs. Why does every element end up counted exactly once? Take an element that lies in exactly \(m \ge 1\) of the sets. It is counted \(\binom{m}{1}\) times in the singles, \(\binom{m}{2}\) times in the pairs, and so on, so its total count is

\[\binom{m}{1} - \binom{m}{2} + \binom{m}{3} - \cdots \pm \binom{m}{m} = 1 - \left(\binom{m}{0} - \binom{m}{1} + \binom{m}{2} - \cdots\right) = 1 - 0 = 1,\]

using the alternating-sum identity from the binomial theorem (put \(x = 1, y = -1\) in \((x + y)^m\)). The two big ideas of the chapter meet here.

24.9.4. Worked example: divisibility

Let \(A_2\), \(A_3\), \(A_5\) be the multiples of 2, 3, 5 in \(\{1, \ldots, 1000\}\). The number of multiples of \(d\) up to \(N\) is \(\lfloor N/d \rfloor\) (the floor, or integer part, of \(N/d\)). A number divisible by both 2 and 3 is divisible by 6, and so on (because 2, 3, 5 are pairwise coprime; see Chapter 23). Try it: Multiples of 2, 3, 5, counted.

\[\begin{aligned} |A_2| + |A_3| + |A_5| &= 500 + 333 + 200 = 1033\\ |A_2 \cap A_3| + |A_2 \cap A_5| + |A_3 \cap A_5| &= \lfloor 1000/6 \rfloor + \lfloor 1000/10 \rfloor + \lfloor 1000/15 \rfloor = 166 + 100 + 66 = 332\\ |A_2 \cap A_3 \cap A_5| &= \lfloor 1000/30 \rfloor = 33\\[4pt] |A_2 \cup A_3 \cup A_5| &= 1033 - 332 + 33 = 734. \end{aligned}\]

So 734 numbers are divisible by at least one of 2, 3, 5, and \(1000 - 734 = 266\) are divisible by none. A one-line brute-force check agrees:

brute = sum(1 for k in range(1, 1001) if k % 2 == 0 or k % 3 == 0 or k % 5 == 0)
formula = (500 + 333 + 200) - (166 + 100 + 66) + 33
print(brute, formula)
734 734
Example 132. Procedure — inclusion–exclusion

Input: sets \(A_1, \ldots, A_k\) whose intersections are easy to count.

Steps:

  1. Compute \(S_1 = \sum |A_i|\) (all singles).

  2. Compute \(S_2 = \sum |A_i \cap A_j|\) over all pairs \(i < j\).

  3. Continue: \(S_t\) is the sum over all \(\binom{k}{t}\) intersections of \(t\) sets.

  4. Combine with alternating signs: \(|A_1 \cup \cdots \cup A_k| = S_1 - S_2 + S_3 - \cdots + (-1)^{k+1} S_k\).

  5. If you want the elements in none of the sets, subtract from the total.

Output: the size of the union (or of its complement).

Hats, letters and 1/e

\(n\) people check their hats; the hats are handed back at random. What is the chance nobody gets their own hat? A permutation with no element in its original place is a derangement. Let \(A_i\) be the permutations that fix person \(i\). Any \(t\) specified people can all get their own hats in \((n-t)!\) ways, so inclusion–exclusion gives

\[D_n = n! - \binom{n}{1}(n-1)! + \binom{n}{2}(n-2)! - \cdots = n! \sum_{t=0}^{n} \frac{(-1)^t}{t!}.\]

For \(n = 4\): \(D_4 = 24(1 - 1 + \tfrac12 - \tfrac16 + \tfrac1{24}) = 12 - 4 + 1 = 9\). The probability \(D_n / n!\) is a partial sum of the series for \(e^{-1}\), so it approaches \(1/e \approx 0.368\) astonishingly fast, and it is essentially the same whether 10 or 10 million people check hats. A Secret Santa draw that must be redrawn whenever someone picks themselves will need, on average, about \(e \approx 2.7\) attempts.

When inclusion–exclusion becomes impractical

With \(k\) sets there are \(2^k - 1\) intersection terms. That’s fine for 3 or 4 sets, or when symmetry makes all \(t\)-fold intersections the same size (as with derangements). Without symmetry and with many sets, the formula is exponential work, and other methods (direct construction, complement, or a program) are better. Also check that the intersections really are what you think: multiples of 4 and of 6 intersect in the multiples of 12, not 24.

24.9.5. Where you’d use this

Everyday: who takes which class. A school has 120 students; 50 take French, 40 Spanish and 30 German; 15 take French and Spanish, 10 French and German, 8 Spanish and German, and 3 take all three. Then \(50 + 40 + 30 - 15 - 10 - 8 + 3 = 90\) take at least one language, so 30 take none. Checking region by region (28 French only, 20 Spanish only, 15 German only, 12, 7 and 5 in exactly two, 3 in all) gives the same 90.

Security: password policies. How many 8-character passwords over the 62 letters and digits contain at least one digit, one lowercase and one uppercase letter? Count the complement with inclusion–exclusion. Passwords missing digits number \(52^8\); missing lowercase, \(36^8\); missing uppercase, \(36^8\). Missing two classes: \(26^8 + 26^8 + 10^8\). Missing all three: 0. So the policy allows Try it: Password policy by inclusion–exclusion.

\[62^8 - (52^8 + 2 \cdot 36^8) + (2 \cdot 26^8 + 10^8) = 159\,655\,911\,367\,680 \approx 1.6 \times 10^{14},\]

about 73% of the \(2.18 \times 10^{14}\) unrestricted strings. Composition rules shrink the keyspace slightly; it is length that grows it.

Science: overlapping risk factors. Epidemiologists use the same bookkeeping on patient records: the number with any of several conditions is the sum of the counts, minus the pairwise overlaps, plus the triple overlap. Forgetting the overlaps overstates prevalence, which is exactly the double counting the formula corrects.

US curriculum

The two-set version, \(P(A \text{ or } B) = P(A) + P(B) - P(A \text{ and } B)\), is the addition rule of probability in Algebra II, Geometry (Common Core S-CP.7) and AP Statistics. The general principle is a college Discrete Mathematics topic.

24.10. The pigeonhole principle

24.10.1. The problem

Some counting questions ask not "how many?" but "must something happen?" In a drawer of black, blue and grey socks, how many must you pull out in the dark to be sure of a matching pair? In any group of 367 people, must two share a birthday?

24.10.2. The principle

Five pigeons in four holes with one hole holding two
Figure 215. Five pigeons, four holes: some hole must hold at least two.

If more than \(k\) objects are placed into \(k\) boxes, some box contains at least two objects.

Proof. If every box held at most one object, there would be at most \(k\) objects. \(\blacksquare\) (A one-line proof by contradiction; see Chapter 22.)

Generalised form. If \(N\) objects go into \(k\) boxes, some box contains at least \(\lceil N/k \rceil\) objects. (Otherwise every box holds at most \(\lceil N/k \rceil - 1 < N/k\) objects, for fewer than \(k \cdot N/k = N\) in total.)

Ceiling and floor

The ceiling \(\lceil x \rceil\) is the smallest integer \(\ge x\): \(\lceil 2.1 \rceil = 3\), \(\lceil 5 \rceil = 5\). The floor \(\lfloor x \rfloor\) is the largest integer \(\le x\): \(\lfloor 2.9 \rfloor = 2\). In code, math.ceil and math.floor; for positive integers, \(\lceil N/k \rceil\) is (N + k - 1) // k and \(\lfloor N/k \rfloor\) is N // k.

The principle is almost embarrassingly obvious. Its power lies in choosing the pigeons and holes cleverly.

24.10.3. Applications, from easy to surprising

  • Socks. Three colours are three holes. Four socks guarantee a matching pair; three do not (one of each colour).

  • Birthdays. There are 366 possible birthdays (including 29 February). So 367 people guarantee a shared birthday. (The probability of a shared birthday is high much earlier, at just 23 people; see Section 24.13.)

  • Hair. Greater London has about 9 million people. Nobody has more than about 200,000 hairs on their head. So the "holes" are the hair counts 0 to 200,000 (200,001 holes), and some hole contains at least \(\lceil 9\,000\,000 / 200\,001 \rceil = 45\) people. At least 45 Londoners have exactly the same number of hairs, and you can say so with certainty without counting anyone’s hair.

  • Handshakes. At any party with \(n \ge 2\) people, two people shook the same number of hands. Each person shook between 0 and \(n - 1\) hands, which looks like \(n\) holes for \(n\) people. But 0 and \(n - 1\) cannot both occur (if someone shook everyone’s hand, nobody shook no hands). So only \(n - 1\) holes are actually available for \(n\) people. You’ll see this again in graph language in Chapter 25.

  • Numbers. Choose any 6 numbers from 1 to 10. Two of them are consecutive. Pair up the holes \(\{1,2\}, \{3,4\}, \{5,6\}, \{7,8\}, \{9,10\}\): five holes, six numbers, so some pair is fully chosen. More generally, any \(n + 1\) numbers from \(1, \ldots, 2n\) include two consecutive ones (and therefore two that share no common factor).

  • Points in a square. Place 5 points in a square of side 2. Some two are within distance \(\sqrt{2}\) of each other. Divide the square into four unit squares (holes); two points share a unit square, and the farthest apart two points in a unit square can be is its diagonal, \(\sqrt{2}\).

Example 133. Procedure — applying the pigeonhole principle

Input: a claim that "some two objects must share a property" (or "some group of at least \(m\) must").

Steps:

  1. Identify the pigeons: the objects you are given (people, numbers, points, files).

  2. Design the holes: categories such that two pigeons in the same hole have the property you want. This is the creative step.

  3. Count: if pigeons \(N >\) holes \(k\), some hole has two; in general some hole has \(\lceil N/k \rceil\).

  4. If the count falls short, look for holes that are impossible to fill simultaneously (as with handshakes) or refine the holes.

Output: a guarantee of existence, usually with no way of telling which hole.

Pigeonhole is non-constructive

The principle proves that a collision exists; it does not tell you where. That’s both its strength (you get a guarantee without searching) and a limitation (if you need the actual pair, you still need an algorithm, such as sorting or hashing to find the duplicate). Also, the bound is only a guarantee for the worst case: with 4 socks you’re sure of a pair, but you will usually get one sooner.

Computer-science connection: why no compressor can shrink everything

A lossless compressor must map different inputs to different outputs, or decompression couldn’t recover the original. Suppose it claims to make every file of exactly \(n\) bits shorter. There are \(2^n\) such files (pigeons). The shorter files, of lengths \(0, 1, \ldots, n - 1\), number

\[2^0 + 2^1 + \cdots + 2^{n-1} = 2^n - 1\]

(holes). Since \(2^n > 2^n - 1\), two inputs must share an output, and the compressor cannot be lossless. So every lossless compressor makes some inputs longer (or at best the same length). Compression works in practice because real files (text, images, logs) are a tiny, highly patterned subset of all possible bit strings, and compressors are tuned to shrink that subset at the expense of random-looking data. Try zipping an already-compressed or encrypted file: it typically grows by a few bytes.

The same argument says every hash function from long inputs to \(b\)-bit digests has collisions: there are more inputs than the \(2^b\) possible digests. Cryptographic hashes do not avoid collisions; they make them infeasible to find.

Where did the pigeons come from?

The principle is often credited to Peter Gustav Lejeune Dirichlet, who used it in 1834 in number theory under the name Schubfachprinzip ("drawer principle"); French and Russian mathematicians still call it the drawer or box principle. The pigeons are a 20th-century English invention, possibly after pigeonholes in a writing desk rather than birds.

US curriculum

The pigeonhole principle is not part of the standard US high-school sequence. Students meet it in math competitions (MATHCOUNTS, AMC, AIME) and in a college Discrete Mathematics course, typically in the first semester of a CS degree.

24.11. Choosing a counting method

24.11.1. The two questions

Most "choose \(r\) things from \(n\) types" problems are settled by two yes/no questions:

  1. Does order matter? Would rearranging the selection give a different outcome?

  2. Is repetition allowed? Can the same item (or type) be chosen more than once?

Order matters (arrangements, sequences) Order doesn’t matter (selections, sets)

Repetition allowed

\(n^r\)
PINs, passwords, bit strings
itertools.product(items, repeat=r)

\(\binom{n+r-1}{r}\)
doughnut boxes, scoops, multisets
itertools.combinations_with_replacement

No repetition

\(P(n, r) = \dfrac{n!}{(n-r)!}\)
podiums, seatings, ordered rankings
itertools.permutations(items, r)

\(\binom{n}{r} = \dfrac{n!}{r!(n-r)!}\)
committees, lottery tickets, poker hands
itertools.combinations(items, r)

Notice how the table is held together by the earlier ideas. Moving down the left column, \(n^r\) becomes \(n(n-1)\cdots\) because each stage loses an option. Moving right along the bottom row, you divide by the \(r!\) orderings. The top-right cell is stars and bars.

Example 134. Procedure — choosing a counting method

Input: a counting question.

Steps:

  1. Is it an existence question ("must two …?", "is there always …?")? Try the pigeonhole principle.

  2. Does it say "at least one", "not all" or "some repeat"? Count the complement and subtract from the total.

  3. Is it a union of overlapping conditions ("divisible by 2 or 3", "contains A or B")? Use inclusion–exclusion.

  4. Does it fit the table? Decide whether order matters and whether repetition is allowed, and use that cell. For arrangements of items with repeated types (MISSISSIPPI), use the multinomial coefficient. For identical objects into distinct boxes, use stars and bars.

  5. Otherwise, break the construction into stages and cases (product and sum rules), checking that each outcome is built exactly once. If a natural construction builds each outcome exactly \(k\) times, divide by \(k\).

  6. Check the answer: by a second method, by a small case you can list by hand, or by a brute-force program.

Output: a count with a method you can justify.

24.11.2. Worked example: one scenario, four answers

From the digits 1–5, form a selection of 3.

  • Ordered, repetition allowed (3-digit codes): \(5^3 = 125\).

  • Ordered, no repetition (3-digit codes with distinct digits): \(5 \cdot 4 \cdot 3 = 60\).

  • Unordered, no repetition (3-element subsets): \(\binom{5}{3} = 10\).

  • Unordered, repetition allowed (multisets such as \(\{1, 1, 4\}\)): \(\binom{5 + 3 - 1}{3} = \binom{7}{3} = 35\).

As a sanity check, the counts must satisfy \(10 \le 35 \le 125\) and \(10 \le 60 \le 125\), since allowing more freedom never reduces the count.

Sanity checks that catch most mistakes
  • Try a tiny case. Shrink the problem until you can list everything (\(n = 3, r = 2\)) and compare with your formula.

  • Compare with neighbouring cells. An unordered count can never exceed the ordered one; a count with restrictions can never exceed the unrestricted one.

  • Check divisibility. If you divided to remove over-counting and the answer isn’t an integer, your over-count factor was wrong.

  • Brute-force it. For small sizes, itertools plus sum(1 for … if …) is a two-line check that you should use freely.

24.12. Applications: lotteries, passwords and poker

24.12.1. Lotteries

A 6/49 lottery draws 6 distinct numbers from 1–49; order doesn’t matter. The number of tickets is

\[\binom{49}{6} = \frac{49 \cdot 48 \cdot 47 \cdot 46 \cdot 45 \cdot 44}{6!} = \frac{10\,068\,347\,520}{720} = 13\,983\,816.\]

One ticket wins the jackpot with probability about 1 in 14 million. US Powerball draws 5 white balls from 69 and 1 red ball from 26: \(\binom{69}{5} \times 26 = 11\,238\,513 \times 26 = 292\,201\,338\) combinations, so the jackpot odds are 1 in about 292 million. A second prize such as "match exactly 5 of 6" in the 6/49 game is a product of combinations: choose 5 of the 6 winning numbers and 1 of the 43 losing numbers, \(\binom{6}{5}\binom{43}{1} = 6 \times 43 = 258\) tickets.

24.12.2. Passwords

A password of length \(L\) over an alphabet of \(a\) symbols has \(a^L\) possibilities (ordered, repetition allowed). Length matters far more than alphabet size, because length is the exponent:

  • 8 lowercase letters: \(26^8 \approx 2.09 \times 10^{11}\).

  • 8 characters from letters and digits: \(62^8 \approx 2.18 \times 10^{14}\).

  • 12 characters from letters and digits: \(62^{12} \approx 3.23 \times 10^{21}\).

Going from 26 to 62 symbols at length 8 multiplies the space by about 1000. Going from length 8 to 12 at 62 symbols multiplies it by \(62^4 \approx 1.5 \times 10^7\). The CS section below turns these counts into cracking times.

24.12.3. Poker hands

A five-card hand from a 52-card deck is an unordered selection without repetition: \(\binom{52}{5} = 2\,598\,960\) hands. Counting particular hands is a perfect exercise in staged construction. The rule: build the hand by deciding the ranks, then the suits, making sure each hand is built once.

Four of a kind (e.g. four 7s and a king). Choose the rank of the four: 13. All four suits are forced: \(\binom{4}{4} = 1\). Choose the fifth card from the 48 others: 48.

\[13 \times 1 \times 48 = 624.\]

Full house (three of one rank, two of another). Choose the rank of the triple, then its suits; choose a different rank for the pair, then its suits:

\[\begin{aligned} 13 \times \binom{4}{3} \times 12 \times \binom{4}{2} &= 13 \times 4 \times 12 \times 6\\ &= 3\,744. \end{aligned}\]

Here the two ranks are chosen in order (13 then 12) because their roles differ: "three kings and two 7s" is a different hand from "three 7s and two kings".

Two pair (two of one rank, two of another, and a fifth card of a third rank). Now the two pair ranks play the same role, so choose them as a set:

\[\begin{aligned} \binom{13}{2} \times \binom{4}{2}^2 \times 44 &= 78 \times 36 \times 44\\ &= 123\,552. \end{aligned}\]

(The fifth card can be any of the \(52 - 8 = 44\) cards not of either pair rank.) If you’d used \(13 \times 12\) for the pair ranks, you’d have built each hand twice and got 247,104.

One pair. Choose the pair rank and suits, then 3 different other ranks (as a set) and a suit for each:

\[13 \times \binom{4}{2} \times \binom{12}{3} \times 4^3 = 13 \times 6 \times 220 \times 64 = 1\,098\,240.\]

Flush (all five the same suit, excluding straight flushes): \(4 \times \binom{13}{5} - 40 = 4 \times 1287 - 40 = 5108\), where 40 is the number of straight flushes (4 suits × 10 possible starting ranks, ace low to ten high).

Dividing by 2,598,960 gives the probabilities: a full house is about 0.144 %, four of a kind about 0.024 %. Rarer hands beat commoner ones, which is exactly the ranking used in the game. That is not a coincidence: the ranking was settled by counting.

Poker-hand counter

Deal random five-card hands and tally the hand types over thousands of deals, side by side with the exact counts above. A "build a hand" mode walks through the stages (rank choices, suit choices) and lets the reader deliberately make the \(13 \times 12\) two-pair mistake and see the over-count.

24.13. Counting in computer science

24.13.1. Keyspaces and brute force

An attacker who has stolen a database of password hashes can guess offline as fast as their hardware allows. For a fast, unsalted hash, a single modern GPU rig can try on the order of \(10^{10}\) guesses per second. The expected time to search the whole keyspace is (keyspace) / (rate); on average the right password is found halfway through. Try it: Password keyspace calculator.

def human(seconds):
    for unit, size in [("years", 365.25 * 86400), ("days", 86400),
                       ("hours", 3600), ("minutes", 60)]:
        if seconds >= size:
            v = seconds / size
            return f"{v:,.1f} {unit}" if v < 1e6 else f"{v:.2e} {unit}"
    return f"{seconds:.2f} seconds"

RATE = 1e10   # guesses per second: a fast offline GPU rig on a weak hash

for name, alphabet, length in [("8 lowercase", 26, 8),
                               ("8 letters+digits", 62, 8),
                               ("12 letters+digits", 62, 12),
                               ("16 printable", 95, 16)]:
    space = alphabet ** length               # product rule
    print(f"{name:18} {space:10.3e} keys   {human(space / RATE)}")
8 lowercase         2.088e+11 keys   20.88 seconds
8 letters+digits    2.183e+14 keys   6.1 hours
12 letters+digits   3.226e+21 keys   10,223.4 years
16 printable        4.401e+31 keys   1.39e+14 years

Two lessons follow. First, exponential growth in length beats everything: every extra character multiplies the work by the alphabet size. Second, these are upper bounds on safety: human-chosen passwords are not uniformly random, so attackers try dictionaries and patterns first, and the effective keyspace is far smaller. That’s why systems use deliberately slow, salted hash functions (bcrypt, scrypt, Argon2) to cut the guess rate by many orders of magnitude, and why a passphrase of 5 random dictionary words (from a list of 7776, as in Diceware) gives \(7776^5 \approx 2.8 \times 10^{19}\) possibilities while staying memorable.

Security engineers express keyspaces in bits: a keyspace of size \(N\) has \(\log_2 N\) bits of entropy (if every key is equally likely). \(62^{12} \approx 2^{71.5}\), so a random 12-character alphanumeric password is a 71-bit secret. A 128-bit AES key gives \(2^{128} \approx 3.4 \times 10^{38}\) keys.

24.13.2. Subsets, \(2^n\) and exponential algorithms

A set of \(n\) elements has \(2^n\) subsets: for each element, "in" or "out". There’s a perfect correspondence between subsets and \(n\)-bit binary numbers (bit \(i\) is 1 if element \(i\) is in), which gives the simplest way to enumerate them:

items = ["a", "b", "c"]
n = len(items)
for mask in range(2 ** n):                       # 0 .. 2^n - 1
    subset = [items[i] for i in range(n) if mask >> i & 1]
    print(f"{mask:03b}", subset)
000 []
001 ['a']
010 ['b']
011 ['a', 'b']
100 ['c']
101 ['a', 'c']
110 ['b', 'c']
111 ['a', 'b', 'c']

Any algorithm that tries every subset (the brute-force approach to subset-sum, knapsack, feature selection or set cover) does at least \(2^n\) units of work, and any algorithm that tries every ordering (brute-force travelling salesman) does \(n!\).

Plot of n squared, 2 to the n and n factorial on a log scale
Figure 216. Polynomial, exponential and factorial growth on a logarithmic scale. At \(10^9\) operations per second, \(2^n\) passes one second near \(n = 30\) and \(n!\) near \(n = 13\).

At a billion operations a second, \(2^{30} \approx 10^9\) subsets take a second, \(2^{40}\) take about 18 minutes, \(2^{50}\) take 13 days, and \(2^{60}\) take 36 years. \(20! \approx 2.4 \times 10^{18}\) orderings take 77 years. Faster hardware barely helps: a computer 1000 times faster raises the feasible \(n\) for a \(2^n\) algorithm by only about 10. This is why the distinction between polynomial and exponential running time is the central dividing line of complexity theory, and why, for problems like these, practical algorithms use pruning, dynamic programming, or approximation instead of enumeration.

24.13.3. Generating permutations

Sometimes you really do need to visit every arrangement: testing all orderings of a small set of operations for race conditions, solving a puzzle exhaustively, or generating test cases. Two standard algorithms do this.

Next permutation (lexicographic order). Given an arrangement, produce the next one in dictionary order. This is what C++'s std::next_permutation does, and it handles repeated items gracefully (it produces each distinct arrangement once).

The idea: to get the next larger arrangement, change as far to the right as possible. Find the longest suffix that is already in descending order (it is the largest possible arrangement of those items, so it can’t be increased by itself). The element just before it, the pivot, must increase, by the smallest possible amount, and then the suffix must be reset to its smallest arrangement (ascending).

Example 135. Procedure — next permutation in lexicographic order

Input: a list \(a_0, a_1, \ldots, a_{n-1}\).

Steps:

  1. Find the largest index \(i\) with \(a_i < a_{i+1}\). If there is none, the list is in descending order: it is the last permutation. Stop (optionally reverse it to wrap around to the first).

  2. Find the largest index \(j > i\) with \(a_j > a_i\). (It exists, since \(a_{i+1} > a_i\).)

  3. Swap \(a_i\) and \(a_j\).

  4. Reverse the suffix \(a_{i+1}, \ldots, a_{n-1}\) (it was descending; now it’s ascending).

Output: the next permutation in lexicographic order. Starting from the sorted list and repeating until step 1 stops visits every distinct permutation exactly once.

Worked trace on \((1, 3, 5, 4, 2)\): Try it: Step through next permutation.

Step Result

1. Pivot

Scanning from the right: \(4 > 2\), \(5 > 4\), but \(3 < 5\). Descending suffix is \((5, 4, 2)\); pivot \(a_1 = 3\).

2. Successor

Rightmost element of the suffix greater than 3: \(a_3 = 4\).

3. Swap

\((1, 4, 5, 3, 2)\)

4. Reverse suffix

\((1, 4, 2, 3, 5)\)

Check: among arrangements starting \(1, 3, \ldots\), \((1, 3, 5, 4, 2)\) is the largest; the next must start \(1, 4\), followed by the remaining \(\{2, 3, 5\}\) in ascending order. That’s \((1, 4, 2, 3, 5)\).

def next_permutation(a):
    """Rearrange list a into the next permutation in lexicographic order.
    Return False (and leave a sorted ascending) if a was the last one."""
    # 1. find the rightmost i with a[i] < a[i+1]  (the "pivot")
    i = len(a) - 2
    while i >= 0 and a[i] >= a[i + 1]:
        i -= 1
    if i < 0:                      # whole list is descending: last permutation
        a.reverse()
        return False
    # 2. find the rightmost j with a[j] > a[i]
    j = len(a) - 1
    while a[j] <= a[i]:
        j -= 1
    # 3. swap pivot with its successor
    a[i], a[j] = a[j], a[i]
    # 4. reverse the suffix so it is as small as possible
    a[i + 1:] = reversed(a[i + 1:])
    return True

a = [1, 2, 3]
out = [a.copy()]
while next_permutation(a):
    out.append(a.copy())
print(out)

b = [1, 3, 5, 4, 2]
next_permutation(b)
print(b)

c = [1, 1, 2]          # repeated items: only distinct arrangements appear
out = [c.copy()]
while next_permutation(c):
    out.append(c.copy())
print(out)
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
[1, 4, 2, 3, 5]
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]

The last line lists \(3!/2! = 3\) arrangements, the multinomial count for \(\{1, 1, 2\}\), not \(3! = 6\).

Backtracking. The other approach builds arrangements position by position, mirroring the product rule’s stages: choose an unused item for the next position, recurse, then undo the choice and try the next item. It is the template for a huge family of search algorithms (sudoku, N-queens, constraint solvers), because you can prune: abandon a partial arrangement as soon as it violates a constraint, skipping every completion of it at once. Try it: Backtracking with pruning (4 queens).

Example 136. Procedure — generate permutations by backtracking

Input: a list of \(n\) distinct items.

Steps:

  1. Keep a partial arrangement (initially empty) and a record of which items are used.

  2. If the partial arrangement has length \(n\), output it and return.

  3. Otherwise, for each unused item \(x\): mark \(x\) used and append it (choose); recurse from step 2 (explore); remove \(x\) and mark it unused (un-choose).

Output: all \(n!\) permutations, each exactly once.

def permutations_bt(items):
    """Generate all orderings of items by backtracking."""
    result, current = [], []
    used = [False] * len(items)

    def extend():
        if len(current) == len(items):        # a complete ordering
            result.append(tuple(current))
            return
        for i, x in enumerate(items):
            if not used[i]:
                used[i] = True                 # choose
                current.append(x)
                extend()                       # explore
                current.pop()                  # un-choose
                used[i] = False

    extend()
    return result

print(permutations_bt("abc"))
print(len(permutations_bt("abcde")))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
120

Choosing between them. In production Python, just use itertools.permutations; it is implemented in C. Use next-permutation when you need to step through arrangements one at a time with constant extra memory, or when items repeat and you want each distinct arrangement once. Use backtracking when you want to prune, which is almost always the case in real search problems.

The recursion tree of the backtracking algorithm is the product-rule tree diagram from Section 24.2: \(n\) branches at the root, \(n - 1\) at the next level, and so on, with \(n!\) leaves.

24.13.4. The birthday paradox and hash collisions

How many people must be in a room for there to be a better than even chance that two share a birthday? The pigeonhole principle says 367 people make it certain; the surprise is how few make it likely.

Count the complement. Assume 365 equally likely birthdays (ignoring 29 February). The number of ways \(n\) people can have all different birthdays is \(P(365, n)\) (ordered, no repetition) out of \(365^n\) total assignments, so

\[\begin{aligned} P(\text{all distinct}) &= \frac{365 \cdot 364 \cdots (365 - n + 1)}{365^n} = \prod_{i=0}^{n-1}\left(1 - \frac{i}{365}\right),\\[4pt] P(\text{some shared birthday}) &= 1 - \prod_{i=0}^{n-1}\left(1 - \frac{i}{365}\right). \end{aligned}\]

(The symbol \(\prod\) is the product version of \(\sum\): multiply the terms instead of adding them.) The probability language is developed properly in Chapter 29; here you need only "favourable over total", with every assignment equally likely.

import math

def p_collision(n, days=365):
    """Probability that at least two of n people share a birthday."""
    p_distinct = 1.0
    for i in range(n):
        p_distinct *= (days - i) / days    # person i+1 avoids the i taken days
    return 1 - p_distinct

for n in (10, 23, 30, 50, 70):
    print(n, round(p_collision(n), 4))

# Hash collisions: with a b-bit hash, about how many items for a 50% chance?
for bits in (32, 64, 128):
    print(bits, f"{math.sqrt(2 * math.log(2) * 2**bits):.3e}")
10 0.1169
23 0.5073
30 0.7063
50 0.9704
70 0.9992
32 7.716e+04
64 5.057e+09
128 2.172e+19
Curve of probability of a shared birthday against group size, crossing one half at 23
Figure 217. The birthday problem: the chance of a shared birthday passes 50 % at just 23 people and 99 % at 57.

Why so few? Because what matters is the number of pairs, not the number of people. 23 people form \(\binom{23}{2} = 253\) pairs, and each pair has a 1-in-365 chance of matching. Using \(1 - x \approx e^{-x}\) for small \(x\),

\[P(\text{all distinct}) \approx \prod_{i=0}^{n-1} e^{-i/N} = e^{-\binom{n}{2}/N} \approx e^{-n^2/(2N)},\]

where \(N\) is the number of possible values. Setting this to \(\tfrac12\) and solving gives \(n \approx \sqrt{2 \ln 2 \cdot N} \approx 1.18\sqrt{N}\). For \(N = 365\), that’s about 22.5. The rule of thumb: collisions become likely after about \(\sqrt{N}\) random items.

Hash collisions. Replace birthdays with hash values. A hash table, a content-addressed store, or a database of short IDs with \(N\) possible values will see its first collision after about \(\sqrt{N}\) items, not \(N\). A 32-bit hash (\(N \approx 4.3 \times 10^9\)) has a 50 % chance of a collision after only about 77,000 items, which is why 32-bit checksums are useless as unique identifiers for large collections. A 64-bit hash reaches 50 % at about 5 billion items. Cryptographic hashes use 256 bits so that the "birthday bound" \(2^{128}\) is far beyond any attacker; a hash with \(b\)-bit output offers only about \(b/2\) bits of collision resistance. The same arithmetic tells you how long random UUIDs (122 random bits) can be generated before a duplicate is plausible: around \(2^{61} \approx 2.3 \times 10^{18}\).

Birthday simulator

Add people one at a time to a virtual room, each with a random birthday, and stop at the first collision; repeat thousands of times and plot the histogram of stopping points against the exact curve. Then switch "days" to \(2^{16}\) or \(2^{24}\) hash buckets and see the \(\sqrt{N}\) rule hold. A password-keyspace calculator sits alongside: choose alphabet, length and guess rate, and watch the time-to-crack move by orders of magnitude as length grows.

Computer-science connection: where counting shows up
  • Algorithm analysis. Counting loop iterations, comparisons or recursive calls is how running time is derived. The number of pairs \(\binom{n}{2}\) is why naive all-pairs algorithms (duplicate detection, collision detection in games, nearest-neighbour search) are quadratic.

  • Testing. Exhaustive testing of \(k\) boolean flags means \(2^k\) configurations. Pairwise (combinatorial) testing instead covers every pair of settings with far fewer test cases, because covering pairs is a much smaller counting target than covering all combinations.

  • Probability and randomised algorithms. Most discrete probability is counting in disguise: favourable outcomes over total outcomes (Chapter 29).

  • Information theory. Specifying one item out of \(N\) equally likely possibilities needs \(\log_2 N\) bits. That’s the link between counting, entropy and compression.

24.14. Interactive tools

Browser tools on the companion website that go with this chapter. Each example link in the chapter opens one of them with that example already set up.

24.15. Exercises

  1. (Recognition) For each scenario, say whether order matters, whether repetition is allowed, and which formula applies: (a) a 5-character licence key using A–Z and 0–9; (b) choosing 4 toppings from 12 for a pizza, no double toppings; (c) assigning first, second and third prizes among 20 entrants; (d) buying 10 bagels from 6 varieties.

  2. (Recognition) Compute \(\binom{7}{3}\), \(\binom{7}{4}\), \(P(7, 3)\) and \(\binom{20}{18}\), and explain why the first two are equal.

  3. (Application) How many 4-digit PINs have digits that are all different and in strictly increasing order (like 1479)?

  4. (Application) Expand \((a - 2b)^4\) using the binomial theorem, and check your answer by substituting \(a = b = 1\).

  5. (Application) How many distinct arrangements are there of the letters of BANANA? How many of them begin with B?

  6. (Application) How many non-negative integer solutions has \(x_1 + x_2 + x_3 + x_4 = 10\)? How many with every \(x_i \ge 2\)?

  7. (Application) How many integers from 1 to 600 are divisible by none of 3, 4 and 5?

  8. (Problem solving) A 5-card poker hand is a straight if its ranks are consecutive (ace may be low, A-2-3-4-5, or high, 10-J-Q-K-A; there are 10 possible rank sequences). Count straights, including straight flushes, and then excluding them.

  9. (Problem solving) Prove that among any 11 integers, two have a difference divisible by 10.

  10. (Problem solving) Give a counting proof that \(\binom{2n}{2} = 2\binom{n}{2} + n^2\). (Hint: a group of \(n\) women and \(n\) men; choose 2 people.)

  11. (Problem solving, CS) A system issues random 6-character IDs from the 36 symbols A–Z, 0–9. Roughly how many IDs can it issue before a collision becomes more likely than not? What about 10-character IDs?

Answers
  1. (a) Order matters, repetition allowed: \(36^5 = 60\,466\,176\). (b) Order doesn’t matter, no repetition: \(\binom{12}{4} = 495\). (c) Order matters, no repetition: \(P(20, 3) = 20 \cdot 19 \cdot 18 = 6840\). (d) Order doesn’t matter, repetition allowed (stars and bars): \(\binom{10 + 6 - 1}{10} = \binom{15}{5} = 3003\).

  2. \(\binom{7}{3} = \frac{7 \cdot 6 \cdot 5}{6} = 35\); \(\binom{7}{4} = 35\) by symmetry (choosing 3 to include is choosing 4 to exclude); \(P(7,3) = 7 \cdot 6 \cdot 5 = 210 = 35 \times 3!\); \(\binom{20}{18} = \binom{20}{2} = 190\).

  3. Any set of 4 distinct digits can be arranged in increasing order in exactly one way, so count sets: \(\binom{10}{4} = 210\).

  4. With \(x = a\), \(y = -2b\), row 4 = 1, 4, 6, 4, 1: \(a^4 + 4a^3(-2b) + 6a^2(4b^2) + 4a(-8b^3) + 16b^4 = a^4 - 8a^3b + 24a^2b^2 - 32ab^3 + 16b^4\). Check: \((1 - 2)^4 = 1\) and \(1 - 8 + 24 - 32 + 16 = 1\). ✓

  5. BANANA: 6 letters with A×3, N×2, B×1: \(\frac{6!}{3!\,2!\,1!} = \frac{720}{12} = 60\). Beginning with B: arrange AAANN in the other 5 positions: \(\frac{5!}{3!\,2!} = 10\).

  6. Free: \(\binom{10 + 4 - 1}{3} = \binom{13}{3} = 286\). With every \(x_i \ge 2\): pre-load 2 each (8 used), distribute the remaining 2: \(\binom{2 + 3}{3} = \binom{5}{3} = 10\).

  7. Multiples: \(|A_3| = 200\), \(|A_4| = 150\), \(|A_5| = 120\); sum 470. Pairs: lcm(3,4)=12 → 50, lcm(3,5)=15 → 40, lcm(4,5)=20 → 30; sum 120. Triple: lcm = 60 → 10. Union: \(470 - 120 + 10 = 360\). None: \(600 - 360 = 240\).

  8. Choose the rank sequence (10 ways), then a suit for each of 5 cards (\(4^5 = 1024\)): \(10 \times 1024 = 10\,240\) straights including straight flushes. Straight flushes: 10 sequences × 4 suits = 40. Excluding them: \(10\,240 - 40 = 10\,200\).

  9. The holes are the 10 possible last digits (remainders 0–9 on division by 10); for negative integers use the remainder in \(\{0, \ldots, 9\}\). Eleven integers, ten holes, so two share a remainder \(r\): \(a = 10p + r\), \(b = 10q + r\), and \(a - b = 10(p - q)\) is divisible by 10.

  10. The left side counts pairs from all \(2n\) people. Split by case: both women \(\binom{n}{2}\), both men \(\binom{n}{2}\), one of each \(n \times n\). The cases are disjoint and cover everything, so \(\binom{2n}{2} = 2\binom{n}{2} + n^2\). (Algebra check: \(\frac{2n(2n-1)}{2} = 2n^2 - n\) and \(n(n-1) + n^2 = 2n^2 - n\). ✓)

  11. \(N = 36^6 \approx 2.18 \times 10^9\); 50 % collision after about \(1.18\sqrt{N} \approx 1.18 \times 46\,656 \approx 55\,000\) IDs. Only fifty-five thousand, despite two billion possible IDs. With 10 characters, \(N = 36^{10} \approx 3.66 \times 10^{15}\), \(\sqrt{N} = 36^5 \approx 6.05 \times 10^7\), so about 71 million IDs.

24.16. Mastery check

  1. In how many ways can 6 books be arranged on a shelf if two particular books must not be next to each other?

  2. A pizza place offers 10 toppings. How many pizzas have exactly 3 different toppings? How many have any number of different toppings (including none)?

  3. Find the coefficient of \(x^2\) in \((3 - x)^6\).

  4. How many ways can 15 identical sweets be shared among 4 children if every child gets at least 2?

  5. A survey of 100 programmers: 60 use Python, 45 use Java, 25 use both. How many use neither?

  6. Show that in any set of 13 people, at least two were born in the same month. How many people guarantee that three share a birth month?

  7. A 4-character code uses digits 0–9 and must contain at least one 7. How many codes are there?

  8. Why can no lossless compression algorithm shrink every 1 MB file?

Decision rule: All correct without hesitation → move on to Chapter 25. Stuck on 1–2 → reread the relevant section (Section 24.11 is the usual culprit). Stuck on more → work the chapter exercises first, checking each answer by brute force in Python.

Mastery check answers
  1. All arrangements: \(6! = 720\). Arrangements with the two books together: glue them, \(5! \times 2! = 240\). Not together: \(720 - 240 = 480\).

  2. Exactly 3: \(\binom{10}{3} = 120\). Any number: each topping in or out, \(2^{10} = 1024\) (the row sum of Pascal’s triangle).

  3. Term \(\binom{6}{k}3^{6-k}(-x)^k\) with \(k = 2\): \(15 \times 81 \times x^2 = 1215x^2\). Coefficient \(1215\).

  4. Give each child 2 first (8 sweets); distribute the remaining 7 freely among 4: \(\binom{7 + 3}{3} = \binom{10}{3} = 120\).

  5. Inclusion–exclusion: \(|P \cup J| = 60 + 45 - 25 = 80\). Neither: \(100 - 80 = 20\).

  6. 13 people, 12 months (holes): some month has \(\lceil 13/12 \rceil = 2\). For three: need \(N\) with \(\lceil N/12 \rceil \ge 3\), so \(N = 25\) (with 24 people it’s possible to have exactly 2 per month).

  7. Complement: all codes \(10^4\), codes with no 7 \(9^4 = 6561\); with at least one 7: \(10\,000 - 6561 = 3439\).

  8. Pigeonhole: there are \(2^n\) files of exactly \(n\) bits (\(n = 8 \times 2^{20}\)) but only \(2^n - 1\) strictly shorter bit strings. A map from all \(n\)-bit files into shorter strings must send two files to the same output, so it can’t be inverted. Every lossless compressor makes some files longer.