Dynamic Programming · Pattern 12 of 12

Combinatorics: count with a formula

Some counting DPs collapse into a formula. Choose where something happens with C(n, k), multiply the options for the rest, and do it all mod 1e9 + 7 with factorials and modular inverses.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Count arrays or strings with an exact number of some event
  • The DP would be dp[i][j] with a simple, symmetric transition
  • The answer is asked modulo 1e9 + 7 and n is up to 10^5

The template

Combinatorics
final int MOD = 1_000_000_007;

long power(long b, long e) {               // fast exponentiation mod MOD
    long r = 1;
    b %= MOD;
    for (; e > 0; e >>= 1, b = b * b % MOD)
        if ((e & 1) == 1) r = r * b % MOD;
    return r;
}

// Arrays with exactly k equal adjacent pairs: choose which k of the n - 1 pairs are equal,
// then m choices for the first value and m - 1 for every "different" step
int countGoodArrays(int n, int m, int k) {
    long[] fact = new long[n];
    fact[0] = 1;
    for (int i = 1; i < n; i++) fact[i] = fact[i - 1] * i % MOD;
    long choose = fact[n - 1] * power(fact[k], MOD - 2) % MOD   // inverse by Fermat: MOD is prime
                  * power(fact[n - 1 - k], MOD - 2) % MOD;
    return (int) (choose * m % MOD * power(m - 1, n - 1 - k) % MOD);
}

The variations

  1. 1Choose the positions, then count the rest

    An array of length n has n - 1 adjacent pairs. Pick the k that are equal with C(n - 1, k). The first value has m options, each "different" pair has m - 1, each "equal" pair has 1. Multiply.

Mistakes to avoid

  • Dividing directly under a modulus: multiply by the modular inverse instead, x^(p - 2) mod p when p is prime.
  • Multiplying two values near 1e9 in a 32-bit int (or a JavaScript number past 2^53): use long, long long or BigInt.
Back to Dynamic Programming →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.