Combinatorics
Counting for computer scientists — sum and product rules, permutations and combinations, binomial coefficients and Pascal's triangle, combinations with repetition (stars and bars), inclusion–exclusion, the pigeonhole principle, Catalan numbers, recurrences, and computing counts modulo a prime.
Combinatorics is the mathematics of counting. Engineers count constantly: how many test cases, how many states a search explores, how large a keyspace is, the probability of a hash collision, how many ways a DP can transition. Good counting turns "it feels slow" into "it's 2ⁿ, so it won't finish for n = 60".
The basic rules
- Sum rule: if a task can be done in one of m ways or one of n (disjoint) ways, there are m + n ways.
- Product rule: if a task is a sequence of a step with m ways and a step with n ways, there are m × n ways.
Examples:
- A password of 8 characters from 62 alphanumerics: . Adding 32 symbols (94 total): . Doubling the length to 16: — length beats complexity.
- IPv4 addresses: billion; IPv6: .
- Subsets of an n-element set: (each element in or out).
Permutations: order matters
The number of ways to arrange n distinct items: .
Arrangements of k items chosen from n:
- Orderings of a 52-card deck: — every well-shuffled deck is almost certainly unique in history.
- Gold, silver, bronze among 10 runners: .
- Arrangements of letters with repeats: "BANANA" has distinct arrangements (divide out identical letters).
Brute-forcing all permutations is O(n!) — feasible to about n = 10–11. The travelling salesman problem by brute force tries (n − 1)!/2 tours.
Combinations: order doesn't matter
Choosing k items from n, ignoring order — the binomial coefficient:
- Poker hands: .
- Pairs among n items: — the number of comparisons in a naive all-pairs algorithm (O(n²)), edges in a complete graph, and handshakes in a room.
- Lattice paths from the top-left to the bottom-right of an m × n grid moving only right or down: — a classic DP problem with a closed form (DP classics).
Pascal's triangle
Either the n-th item is chosen (choose k − 1 from the rest) or not (choose k from the rest). This recurrence is itself a dynamic program:
def binomial_table(n):
C = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n + 1):
C[i][0] = 1
for k in range(1, i + 1):
C[i][k] = C[i - 1][k - 1] + C[i - 1][k]
return C
print(binomial_table(5)[5]) # [1, 5, 10, 10, 5, 1]The binomial theorem: . Setting x = y = 1 gives — the number of subsets again.
Combinations with repetition (stars and bars)
The number of ways to choose k items from n types with repetition (or distribute k identical items into n bins) is:
Picture k stars separated by n − 1 bars. E.g. buying 10 samosas from 3 flavours: ways.
Inclusion–exclusion
To count a union, add the individual sets, subtract pairwise overlaps, add back triple overlaps, and so on:
Numbers from 1 to 100 divisible by 2, 3 or 5: 50 + 33 + 20 − 16 − 10 − 6 + 3 = 74.
Derangements (permutations with no element in its original place — "no one gets their own gift" in a secret Santa): . About 37% of random permutations are derangements.
The pigeonhole principle
If n items go into m containers and n > m, some container holds at least two items. More generally, some container holds at least .
Simple, yet powerful:
- Hash collisions are unavoidable when there are more possible keys than buckets (Hash tables).
- Lossless compression can't shrink every file: there are files of n bits but only shorter ones.
- Among any 13 people, two share a birth month. In a sliding window of size 27 over lowercase letters, some letter repeats.
- Interview classic: in an array of n + 1 integers from 1 to n, some value repeats (find it with Floyd's cycle detection).
The birthday paradox is a probabilistic cousin: collisions become likely after only ~ items, not m (Probability, Hash functions).
Catalan numbers
They count a surprising number of structures:
- Valid sequences of n pairs of parentheses.
- Structurally different binary trees with n nodes (and BSTs on n distinct keys — "Unique BSTs" on LeetCode).
- Ways to triangulate a convex polygon with n + 2 sides.
- Mountain ranges / Dyck paths; ways to fully parenthesise a product of n + 1 matrices.
They satisfy — choose a root, then count left and right subtrees — a natural DP.
Counting in algorithm analysis
| Structure | Count | Feasible n for brute force |
|---|---|---|
| Pairs | ~10⁴–10⁵ | |
| Triples | ~10³ | |
| Subsets | ~20–25 | |
| Permutations | ~10–11 |
These counts tell you which approach can possibly fit in a time limit before you write any code (Complexity analysis).
Counting modulo a prime
Counts explode quickly, so programming problems ask for answers modulo (a prime). Precompute factorials and use modular inverses (Fermat's little theorem: ) to compute in O(1) per query:
MOD = 10**9 + 7
N = 10**6
fact = [1] * (N + 1)
for i in range(1, N + 1):
fact[i] = fact[i - 1] * i % MOD
inv_fact = [1] * (N + 1)
inv_fact[N] = pow(fact[N], MOD - 2, MOD) # Fermat inverse
for i in range(N, 0, -1):
inv_fact[i - 1] = inv_fact[i] * i % MOD
def nCr(n, k):
if k < 0 or k > n: return 0
return fact[n] * inv_fact[k] % MOD * inv_fact[n - k] % MOD- Sum rule for alternatives, product rule for sequences of choices.
- Permutations count arrangements (n!, P(n, k)); combinations count selections (n choose k).
- Pascal's rule builds binomial coefficients by DP; stars and bars counts selections with repetition.
- Inclusion–exclusion counts unions; derangements are about n!/e.
- Pigeonhole: more items than boxes forces a collision — hashing, compression, duplicate-finding.
- Catalan numbers count parentheses, binary trees and triangulations.
- Use counts to judge brute-force feasibility; compute large counts modulo a prime with factorials and inverses.