Lesson 45 · Core algorithms

Combinatorics Basics

Combinatorics counts arrangements without listing them. A few rules cover most coding problems: add for separate cases, multiply for steps in a row, divide out orders you do not care about, and subtract overlaps.

Combinatorics Basics concept diagramA visual explanation of the layout and operations shown in this lesson.why C(4,2) = C(3,1) + C(3,2): split on one elementabcdchoose 2 from {a, b, c, d} — every choice either uses d, or does notuses dpick 1 more from {a, b, c}C(3,1) = 3 waysskips dpick 2 from {a, b, c}C(3,2) = 3 waysC(4,2) = 3 + 3 = 6the two cases never overlap and miss nothing, so the counts simply addthat argument is Pascal's rule, and it is why the triangle is built by addition
1

Sum Rule and Product Rule

Most of combinatorics basics rests on two rules. The sum rule: if a choice falls into one of several cases that cannot happen together, add the counts of each case. The product rule: if a choice is made in steps, multiply the number of options at each step, as long as that number does not depend on what was picked earlier.

Picking a captain and then a vice-captain from 5 people is 5 × 4 = 20: five options, then four. A 4-digit PIN is 10⁴ = 10,000, since digits may repeat. Before using any formula, be able to say which one object each counted choice stands for; most wrong answers count some objects twice or count things that are not valid objects.

  • Add for separate cases
  • Multiply for steps in a row
2

Permutations and Combinations

Permutations count arrangements where order matters. All n distinct items can be ordered in n! ways; choosing and ordering r of them gives P(n, r) = n!/(n − r)!.

Combinations count selections where order does not matter. Each set of r items appears in r! orders among the permutations, so C(n, r) = n!/(r!·(n − r)!), read "n choose r" and written nCr. This number is the binomial coefficient, because it is the coefficient of xʳ in (1 + x)ⁿ. Choosing a team of 2 from 5 is 20/2 = 10.

Repeated items reduce the count. The letters of MISSISSIPPI (11 letters: 4 I, 4 S, 2 P, 1 M) can be ordered in 11!/(4!·4!·2!) = 34,650 distinct ways, because swapping two identical letters changes nothing.

Which formula: order and repetition
Repetition not allowedRepetition allowed
Order mattersP(n, r) = n!/(n − r)!nʳ
Order does not matterC(n, r) = n!/(r!(n − r)!)C(n + r − 1, r)
  • Permutations: order matters
  • Combinations: divide out the r! orders
3

Pascal's Rule and Computing nCr

Fix one item. Every r-subset either contains it, leaving r − 1 to pick from the other n − 1, or does not, leaving r to pick from n − 1. So C(n, r) = C(n − 1, r − 1) + C(n − 1, r), with C(n, 0) = C(n, n) = 1. Filling these values row by row gives Pascal's triangle in O(n·r) additions and no division, which also works under any modulus.

For one value, use the product C(n, r) = ∏ (n − r + i)/i for i = 1..r, multiplying before dividing; every partial result is itself a binomial coefficient, so each division is exact. Use r = min(r, n − r) to shorten the loop. Never compute n! first: 21! already exceeds 64 bits, while C(30, 15) = 155,117,520 fits easily.

For many queries modulo a prime p (such as 10⁹ + 7) with n < p, precompute factorials and their inverses once in O(n), then answer each C(n, r) = n!·(r!)⁻¹·((n − r)!)⁻¹ mod p in O(1). The inverses come from Fermat's little theorem; see the number theory basics lesson. For n ≥ p use Lucas's theorem.

  • Pascal's rule: addition only, any modulus
  • Multiply before dividing in the product formula
  • Factorials plus inverse factorials for many queries mod p
Key reference

Terms, operations, and practical uses

Counting choices

  • Product ruleSteps made in a row multiply: a choices then b choices give a × b outcomes.
  • PermutationAn ordered arrangement. P(n, r) = n!/(n − r)! ways to pick and order r of n items.
  • CombinationAn unordered selection. C(n, r) = n!/(r!(n − r)!), the permutations divided by the r! orders of each set.

Computing nCr

  • Pascal's ruleC(n, r) = C(n − 1, r − 1) + C(n − 1, r): include or exclude one item. Addition only.
  • Multiplicative formulaMultiply by (n − r + i) then divide by i for i = 1..r; each division is exact.
  • Inverse factorialsPrecomputed (i!)⁻¹ mod p give O(1) answers mod a prime p when n < p.

Other tools

  • Stars and barsk identical items into n boxes: C(k + n − 1, n − 1) arrangements of stars and bars.
  • Inclusion–exclusionSize of a union of overlapping sets: add singles, subtract pairs, add triples, and so on.
  • DerangementAn ordering with no item in its own place: 9 of the 24 orderings of 4 items.
Implementation

Code in Python, C++ and Java

n, r = 5, 2
dp = [[0] * (r + 1) for _ in range(n + 1)]
for i in range(n + 1):
    dp[i][0] = 1
    for j in range(1, min(i, r) + 1):
        dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
print("C(5,2):", dp[n][r])
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n = 5, r = 2;
    vector<vector<long long>> dp(n + 1, vector<long long>(r + 1, 0));
    for (int i = 0; i <= n; i++) {
        dp[i][0] = 1;
        for (int j = 1; j <= min(i, r); j++) dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
    }
    cout << "C(5,2): " << dp[n][r] << '\n';
}
class Main {
    public static void main(String[] args) {
        int n = 5, r = 2;
        long[][] dp = new long[n + 1][r + 1];
        for (int i = 0; i <= n; i++) {
            dp[i][0] = 1;
            for (int j = 1; j <= Math.min(i, r); j++) dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
        }
        System.out.println("C(5,2): " + dp[n][r]);
    }
}
Watch it run

Step through it

Running on people A, B, C, D, E; team size 2

choose 2 of A, B, C, D, E: order matters1st ↓ 2nd →ABCDEA—ABACADAEBBA—BCBDBECCACB—CDCEDDADBDC—DEEEAEBECED—product rule:5 choices, then 4 choices5 × 4 = 20 ordered pairsP(5, 2) = 20
Step 1

Captain and vice: 5 × 4 = 20

Pick a captain (5 choices), then a vice-captain from the other 4. By the product rule that is 5 × 4 = 20 ordered pairs, one per blue cell. The diagonal is empty because one person cannot hold both jobs. This count, where order matters, is the permutation P(5, 2) = 5!/3!.

Output
1 / 12
4

Stars and Bars

How many ways can k identical items go into n distinct boxes? Line the items up as k stars and place n − 1 bars between them to mark where one box ends and the next begins. Every arrangement of k stars and n − 1 bars is one way, so the count is C(k + n − 1, n − 1).

Three identical sweets for three children: 3 stars and 2 bars in 5 slots, C(5, 2) = 10. The same count answers "how many solutions does x₁ + x₂ + x₃ = 3 have in non-negative integers". If every box must get at least one item, hand one to each box first: the count becomes C(k − 1, n − 1).

  • Identical items, distinct boxes
  • At least one per box: C(k − 1, n − 1)
5

Inclusion–Exclusion Principle

When groups overlap, adding their sizes counts the shared items more than once. For two sets, |A ∪ B| = |A| + |B| − |A ∩ B|. For three, add the singles, subtract the pairs and add back the triple. The inclusion exclusion principle continues with alternating signs.

Why it works: an item that lies in exactly k of the sets is counted C(k, 1) − C(k, 2) + C(k, 3) − … = 1 time, so every item in the union counts once. A classic use is derangements, orderings where nobody stays in place: for 4 items it gives 24 − 24 + 12 − 4 + 1 = 9.

  • Subtract overlaps, add back triple overlaps
  • Each item in the union ends up counted once
6

Edge Cases and Checks

C(n, 0) = 1: there is exactly one way to choose nothing. C(n, r) = 0 when r > n or r < 0, and code should return that directly rather than take the factorial of a negative number. 0! = 1.

Overflow and order of operations cause most bugs: r *= (n − k + i) / i truncates before it multiplies and gives 8 for C(5, 2). For small inputs, check any formula against a brute-force count. Related problem pages: Pascal's triangle, unique paths (C(m + n − 2, m − 1)), combinations and permutation sequence.

  • Choosing nothing counts once; impossible choices count zero
  • Compare with brute force on small cases