Combinatorics & Counting
Counting is the arithmetic of finite sets. We build up from permutations $n!
╌╌╌╌
Modular exponentiation and, through Fermat's little theorem, the modular inverse underlie most of practical combinatorics: almost every counting answer is a ratio of factorials, and a ratio modulo a prime is a product with an inverse. This lesson covers the counting tools (permutations, combinations, Pascal's rule, stars and bars) and then shows how to evaluate those quantities modulo a prime in constant time after a linear precompute. We finish with two structural principles: inclusion–exclusion for counting unions, and the Chinese Remainder Theorem for combining congruences.
Permutations and combinations
A permutation is an ordering of distinct objects. There are choices for the first position, for the second, and so on, giving
If we order only of the objects, we stop the product after factors:
A combination counts subsets of size , where orderings no longer matter. Each -subset can be ordered in ways, so dividing by removes the overcount:
The quantity , read choose ,
is the binomial coefficient.1
It is symmetric, (choosing which to include is the
same as choosing which to exclude), and the two boundary values are
.
Pascal's rule
Binomial coefficients satisfy a recurrence that lets us build them additively, with no division at all:
Arranging these values in rows is Pascal's triangle: each interior entry is the sum of the two directly above it.
The highlighted cell is . Because each entry needs only the row above, the whole triangle up to row is an dynamic program, the right approach when is small or when no modulus is involved (and the basis for Pascal's Triangle II and grid-path problems like Unique Paths, whose answer is exactly ).
That grid-path count is Pascal's rule in disguise: label each lattice node with the number of monotone (right/down) paths reaching it, and each node is the sum of its left and top neighbours, exactly the additive recurrence. On a grid of nodes the corner reads .
The binomial theorem
The name binomial coefficient
comes from the expansion of .
Setting gives : the number of subsets of an -set, counted by size.
Combinations with repetition: stars and bars
How many ways can we write a non-negative integer as an ordered sum of non-negative parts, with each ? Equivalently, how many multisets of size can we draw from distinct types?
Concretely, with and there are slots; choosing the of them that hold bars fixes the three part sizes at once, so the count is .
Computing
Competitive and large-scale problems ask for counts modulo a prime (typically ) because the true values are astronomically large. The factorial formula has a division by , and division is not defined modulo ; what stands in for it is multiplication by a modular inverse. Since is prime, Fermat gives for any , computed by the modular exponentiation routine.
The plan: precompute the factorials for all , and the inverse factorials . With both tables in hand, every binomial coefficient is a single product.
- 1
- 2for to do
- 3
- 4one Fermat inverse
- 5for downto do
- 6peel a factor
The downward loop is the trick that keeps the precompute at rather than : only one modular exponentiation is needed, for ; each smaller inverse factorial follows from . Then each query is constant time:
This -precompute, -query scheme is what Number of Music Playlists and Count Anagrams need, since both reduce to products and ratios of factorials modulo .
Worked example ( modulo a small prime). Take and compute , which is . Build the factorial table : , giving . We need the two inverse factorials and . Fermat gives , and the downward peel fills the rest; the entries we want come out to (since and ) and (since and ). Then
matching . The single Fermat inverse plus a linear peel is all the division the whole computation ever does.
Inclusion–exclusion
To count a union of overlapping sets we cannot simply add their sizes, since elements in several sets get counted several times. Inclusion–exclusion corrects the overcount with alternating signs:
Worked example (counting coprime-to-a-set integers). How many integers in are divisible by none of ? Let be the multiples of respectively. Then ; ; and . So
leaving integers divisible by none of , which are exactly
. The same alternating sum, applied with = maps position to itself,
counts derangements .
Worked example (derangements of four items). How many permutations of leave no element fixed? Let be the permutations fixing position . There are ways to fix a chosen set of positions and permute the rest, so inclusion–exclusion gives
Those nine derangements are the permutations that leave no number in its own slot — for instance , , — and the ratio is already close to the limiting value that approaches, since the alternating sum is the truncated series for .
The Chinese Remainder Theorem
Inclusion–exclusion combines counts; the Chinese Remainder Theorem (CRT) combines congruences. Given a system
with the moduli pairwise coprime, CRT guarantees a unique solution modulo .4 The construction is explicit and again uses the modular inverse. Let . Because the are coprime to , so is , hence has an inverse modulo ; call it (or when is prime). Then
Each term is (since there) and modulo every other (since ), so the sum satisfies all congruences simultaneously. Concretely, to solve and each term acts as a selector: one lands on its own residue and vanishes modulo the other, so adding them assembles the answer one congruence at a time.
- 1
- 2
- 3for to do
- 4
- 5
- 6
- 7return
CRT lets us compute modulo a large composite by working independently in each prime-power factor and reassembling the results.
Catalan numbers, generating functions, and symmetry
The four tools above cover most counting problems, but a few structural ideas from enumerative combinatorics recur often enough to name.
Catalan numbers. The count answers many
distinct-looking questions: balanced-parenthesis strings of
pairs, binary trees on nodes, triangulations of an -gon, and monotone
lattice paths that stay below the diagonal. All reduce to the same recurrence
, whose closed form is the ratio of
binomials above — so with the factorial tables already built, any Catalan count is
one query.5 The reflection-principle proof (count all paths, subtract
the bad
ones by reflecting across the boundary) explains
the factor.
Generating functions. Treating a counting sequence as the coefficients of a formal power series turns recurrences into algebra: the Fibonacci generating function is the rational , and stars-and-bars is just the coefficient extraction . Products of generating functions are convolutions, which is why the Fast Fourier Transform later in this module multiplies two counting sequences in .6
Counting up to symmetry (Burnside). When arrangements that differ by a rotation
or reflection should count once — necklaces, colorings of a cube's faces — naive
counting over-counts by the symmetry group. Burnside's lemma says the number of
distinct arrangements equals the average number of arrangements fixed by each
symmetry, , and Pólya enumeration
packages this into generating functions.7 These are the standard route to
count the distinct colorings
problems that inclusion–exclusion alone cannot handle.
Takeaways
- Permutations count orderings (, or ); combinations count subsets, , dividing out the orderings.
- Pascal's rule (element in or out) builds the triangle additively in with no division.
- Stars and bars: the ordered non-negative solutions of number , via the bars-between-stars bijection.
- To compute , precompute factorials and inverse factorials (one Fermat inverse, then peel factors) in , giving per query; use Lucas' theorem when .
- Inclusion–exclusion counts unions by alternating add/subtract over all intersections; the alternating signs make each element net-counted exactly once.
- The Chinese Remainder Theorem uniquely solves a system of congruences with coprime moduli via , the inverse again coming from Fermat or the extended gcd.
Footnotes
- CLRS, Appendix C — Counting and Probability (§C.1): permutations, combinations, and the binomial coefficient . ↩
- Skiena, § — Combinatorics: Lucas' theorem reduces to a product of base- digit binomials when exceed . ↩
- CLRS, Appendix C — Counting and Probability (§C.1): the inclusion–exclusion principle and the alternating-sign correction for unions. ↩
- CLRS, Ch. 31 — Number-Theoretic Algorithms (§31.5): the Chinese Remainder Theorem and the constructive formula. ↩
- R. P. Stanley, Enumerative Combinatorics, Vol. 2, Cambridge University Press, 1999 (Catalan numbers, Exercise 6.19 and its 66+ interpretations). ↩
- H. S. Wilf, generatingfunctionology, 2nd ed., Academic Press, 1994 — the standard treatment of ordinary and exponential generating functions. ↩
- N. G. de Bruijn,
Pólya's theory of counting,
in Applied Combinatorial Mathematics (Beckenbach, ed.), 1964; the counting-by-group-action lemma is also in Skiena, § — Combinatorics. ↩
╌╌ END ╌╌