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.

Intermediate 5 min readLesson 3 of 9

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: 628≈2.2×101462^8 \approx 2.2 \times 10^{14}. Adding 32 symbols (94 total): 948≈6.1×101594^8 \approx 6.1 \times 10^{15}. Doubling the length to 16: 6216≈4.8×102862^{16} \approx 4.8 \times 10^{28} — length beats complexity.
  • IPv4 addresses: 232≈4.32^{32} \approx 4.3 billion; IPv6: 21282^{128}.
  • Subsets of an n-element set: 2n2^n (each element in or out).

Permutations: order matters

The number of ways to arrange n distinct items: n!=n×(n−1)×⋯×1n! = n \times (n-1) \times \cdots \times 1.

Arrangements of k items chosen from n:

P(n,k)=n!(n−k)!P(n, k) = \frac{n!}{(n - k)!}
  • Orderings of a 52-card deck: 52!≈8×106752! \approx 8 \times 10^{67} — every well-shuffled deck is almost certainly unique in history.
  • Gold, silver, bronze among 10 runners: P(10,3)=720P(10, 3) = 720.
  • Arrangements of letters with repeats: "BANANA" has 6!3! 2! 1!=60\frac{6!}{3!\,2!\,1!} = 60 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:

(nk)=n!k! (n−k)!\binom{n}{k} = \frac{n!}{k!\,(n-k)!}
  • Poker hands: (525)=2,598,960\binom{52}{5} = 2{,}598{,}960.
  • Pairs among n items: (n2)=n(n−1)2\binom{n}{2} = \frac{n(n-1)}{2} — 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: (m+nm)\binom{m+n}{m} — a classic DP problem with a closed form (DP classics).

Pascal's triangle

(nk)=(n−1k−1)+(n−1k)\binom{n}{k} = \binom{n-1}{k-1} + \binom{n-1}{k}

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:

Python
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: (x+y)n=∑k(nk)xkyn−k(x + y)^n = \sum_k \binom{n}{k} x^k y^{n-k}. Setting x = y = 1 gives ∑k(nk)=2n\sum_k \binom{n}{k} = 2^n — 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:

(n+k−1k)\binom{n + k - 1}{k}

Picture k stars separated by n − 1 bars. E.g. buying 10 samosas from 3 flavours: (1210)=66\binom{12}{10} = 66 ways.

Inclusion–exclusion

To count a union, add the individual sets, subtract pairwise overlaps, add back triple overlaps, and so on:

∣A∪B∪C∣=∣A∣+∣B∣+∣C∣−∣A∩B∣−∣A∩C∣−∣B∩C∣+∣A∩B∩C∣\lvert A \cup B \cup C \rvert = \lvert A \rvert + \lvert B \rvert + \lvert C \rvert - \lvert A \cap B \rvert - \lvert A \cap C \rvert - \lvert B \cap C \rvert + \lvert A \cap B \cap C \rvert

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): Dn=n!∑i=0n(−1)ii!≈n!/eD_n = n! \sum_{i=0}^{n} \frac{(-1)^i}{i!} \approx n!/e. 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 ⌈n/m⌉\lceil n/m \rceil.

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 2n2^n files of n bits but only 2n−12^n - 1 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 ~m\sqrt{m} items, not m (Probability, Hash functions).

Catalan numbers

Cn=1n+1(2nn):1,1,2,5,14,42,132,429,…C_n = \frac{1}{n+1}\binom{2n}{n} : \quad 1, 1, 2, 5, 14, 42, 132, 429, \ldots

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 Cn+1=∑i=0nCiCn−iC_{n+1} = \sum_{i=0}^{n} C_i C_{n-i} — choose a root, then count left and right subtrees — a natural DP.

Counting in algorithm analysis

StructureCountFeasible n for brute force
Pairs(n2)≈n2/2\binom{n}{2} \approx n^2/2~10⁴–10⁵
Triples(n3)≈n3/6\binom{n}{3} \approx n^3/6~10³
Subsets2n2^n~20–25
Permutationsn!n!~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 109+710^9 + 7 (a prime). Precompute factorials and use modular inverses (Fermat's little theorem: a−1≡ap−2(modp)a^{-1} \equiv a^{p-2} \pmod p) to compute (nk)\binom{n}{k} in O(1) per query:

Python
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
Key takeaways
  • 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.