Skip to main content

Combinatorics

Basics of counting

Binomial coefficient patterns: “choose the positions”

When you need to place kk identical “special markers” into nn distinct slots (or choose which kk items are special), the count is

(nk)\binom{n}{k}

Classic example: number of binary strings of length nn with exactly kk ones is (nk)\binom{n}{k} (choose the kk positions of the ones).

Practice


Computing (nk)\binom{n}{k} with factorials + inverse factorials (mod prime)

Many problems may require you to compute many instances of (nk)modp\binom{n}{k} \bmod p for a fixed prime pp (commonly 109+710^9+7).
We use:

(nk)n!k!(nk)!(modp)\binom{n}{k} \equiv \frac{n!}{k!(n-k)!} \pmod p

and modular inverses (division mod pp).

Fermat inverse (prime modulus)

If pp is prime and a≢0(modp)a \not\equiv 0 \pmod p, then:

a1ap2(modp)a^{-1} \equiv a^{p-2} \pmod p

Precomputation plan

Let NN be the maximum nn we will need.

  • Precompute fact[i] = i! mod p for 0iN0 \le i \le N
  • Precompute invfact[i] = (i!)^{-1} mod p for 0iN0 \le i \le N - use binary exponentiation to compute the powers.
  • Then each query is O(1)O(1):
(nk)=fact[n]invfact[k]invfact[nk](modp)\binom{n}{k} = \text{fact}[n] \cdot \text{invfact}[k] \cdot \text{invfact}[n-k] \pmod p

Practice


Stars and Bars

Core statement

Number of solutions in nonnegative integers to

x1+x2++xn=m,xi0x_1 + x_2 + \cdots + x_n = m, \quad x_i \ge 0

is

(m+n1n1)\binom{m+n-1}{n-1}

Common variations

  • If xi1x_i \ge 1, substitute yi=xi1y_i = x_i - 1: x1++xn=m, xi1    y1++yn=mn, yi0x_1+\cdots+x_n=m,\ x_i\ge 1 \iff y_1+\cdots+y_n=m-n,\ y_i\ge 0 so the count is (m1n1)\binom{m-1}{n-1} (when mnm\ge n).
  • If xiLix_i \ge L_i, substitute yi=xiLiy_i = x_i - L_i and reduce the sum.

Practice


Principle of Inclusion-Exclusion (PIE)

PIE is the standard way to count “avoid all of these bad properties” when overlaps exist.

Formula (union size)

For sets A1,,AkA_1,\dots,A_k:

i=1kAi=S[k](1)S+1iSAi\left|\bigcup_{i=1}^k A_i\right| = \sum_{\emptyset \ne S \subseteq [k]} (-1)^{|S|+1} \left|\bigcap_{i\in S} A_i\right|

When kk is up to ~20-25, iterating all 2k2^k subsets is feasible.

For many PIE counting tasks:

  • Define the intersection size for a subset SS
  • Add/subtract it depending on parity of S|S|

Practice


General Problems: