DSA · Competitive Programmer · Pattern 2 of 9
Combinatorics & Modular Arithmetic
12 problems.
Your progress0%
- 1st Visit
- 0/12
- 2nd Visit
- 0/12
- Revise
- 0/12
About this pattern
Counting problems ask for the number of arrangements, sequences or selections, usually modulo a prime such as 1e9+7 or 998244353. Precompute factorials and inverse factorials once and evaluate C(n, k) in O(1); modular inverses come from Fermat's little theorem because the modulus is prime. The difficulty lies in the reduction: stars and bars for monotone sequences, multiplying independent choices, inserting elements one at a time, or fixing one parameter such as the smallest value or the peak and summing over it. Signals include answers that are far too large to print directly, a required modulus, and structures such as monotone arrays or interleavings.
const int MOD = 1'000'000'007, N = 2'000'005;
long long fact[N], inv[N];
long long power(long long b, long long e) {
long long r = 1; b %= MOD;
for (; e > 0; e >>= 1, b = b * b % MOD) if (e & 1) r = r * b % MOD;
return r;
}
void init() {
fact[0] = 1;
for (int i = 1; i < N; i++) fact[i] = fact[i - 1] * i % MOD;
inv[N - 1] = power(fact[N - 1], MOD - 2);
for (int i = N - 1; i > 0; i--) inv[i - 1] = inv[i] * i % MOD;
}
long long C(int n, int k) {
if (k < 0 || k > n) return 0;
return fact[n] * inv[k] % MOD * inv[n - k] % MOD;
}