Combinatorics
Basics of counting
Binomial coefficient patterns: “choose the positions”
When you need to place identical “special markers” into distinct slots (or choose which items are special), the count is
Classic example: number of binary strings of length with exactly ones is (choose the positions of the ones).
Practice
Computing with factorials + inverse factorials (mod prime)
Many problems may require you to compute many instances of for a fixed prime (commonly ).
We use:
and modular inverses (division mod ).
Fermat inverse (prime modulus)
If is prime and , then:
Precomputation plan
Let be the maximum we will need.
- Precompute
fact[i] = i! mod pfor - Precompute
invfact[i] = (i!)^{-1} mod pfor - use binary exponentiation to compute the powers. - Then each query is :
Practice
Stars and Bars
Core statement
Number of solutions in nonnegative integers to
is
Common variations
- If , substitute : so the count is (when ).
- If , substitute 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 :
When is up to ~20-25, iterating all subsets is feasible.
For many PIE counting tasks:
- Define the intersection size for a subset
- Add/subtract it depending on parity of