Skip to content
We areTOP 1%
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;
}

Problems

Combinatorics & Modular Arithmetic questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Two ArraysCodeforcesMedium 1600Solve Two Arrays on Codeforces (opens in a new tab)
2Count All Valid Pickup and Delivery OptionsLeetCodeHard Solve Count All Valid Pickup and Delivery Options on LeetCode (opens in a new tab)
3Count the ArraysCodeforcesMedium 1700Solve Count the Arrays on Codeforces (opens in a new tab)
4Count AnagramsLeetCodeHard Solve Count Anagrams on LeetCode (opens in a new tab)
5AquaMoon and ChessCodeforcesHard 1900Solve AquaMoon and Chess on Codeforces (opens in a new tab)
6Divide and SumCodeforcesHard 1900Solve Divide and Sum on Codeforces (opens in a new tab)
7Number of Ways to Reorder Array to Get Same BSTLeetCodeHard Solve Number of Ways to Reorder Array to Get Same BST on LeetCode (opens in a new tab)
8Modular StabilityCodeforcesHard 2000Solve Modular Stability on Codeforces (opens in a new tab)
9Coprime SubsequencesCodeforcesHard 2000Solve Coprime Subsequences on Codeforces (opens in a new tab)
10Count the Number of Ideal ArraysLeetCodeHard Solve Count the Number of Ideal Arrays on LeetCode (opens in a new tab)
11Gerald and Giant ChessCodeforcesHard 2200Solve Gerald and Giant Chess on Codeforces (opens in a new tab)
12Devu and FlowersCodeforcesHard 2300Solve Devu and Flowers on Codeforces (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account