Skip to content

Latest commit

 

History

History

Combinatorics

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Combinatorics Utilities

Essential combinatorics functions for competitive programming and technical interviews.

Quick Reference

Function Formula Time Complexity Use Case
factorial(n) n! O(1)* Count total arrangements
nCr(n, r) n! / (r! × (n-r)!) O(1)* Choose r items from n
nPr(n, r) n! / (n-r)! O(1)* Arrange r items from n
catalan(n) C(2n,n) / (n+1) O(1)* BSTs, parentheses, paths
starsAndBars(n, k) C(n+k-1, k-1) O(1)* Distribute identical items
derangements(n) n! × Σ((-1)^i / i!) O(n) No fixed point permutations

*After O(n) precomputation


Core Concepts

1. Combinations (nCr)

"How many ways to choose?" - Order doesn't matter.

Formula: C(n, r) = n! / (r! × (n-r)!)

Use Cases:

  • Selecting teams from a group
  • Choosing items from a set
  • Counting subsets of specific size
  • Grid paths (right/down movements)

Example Problems:


2. Permutations (nPr)

"How many ways to arrange?" - Order matters.

Formula: P(n, r) = n! / (n-r)!

Use Cases:

  • Arranging people in seats
  • Password generation
  • Race finishing orders
  • Scheduling problems

Example Problems:


3. Catalan Numbers

"How many valid structures?"

Formula: C(n) = C(2n, n) / (n+1)

Common Use Cases:

Problem Type Catalan Number
Valid parentheses with n pairs C(n)
Unique BSTs with n nodes C(n)
Paths below diagonal (n×n grid) C(n)
Ways to triangulate (n+2)-gon C(n)
Mountain ranges with n upstrokes C(n)

Example Problems:

Sequence: 1, 1, 2, 5, 14, 42, 132, 429...


4. Stars and Bars

"Distribute n identical items into k distinct bins"

Formula: C(n + k - 1, k - 1)

Use Cases:

  • Distribute identical balls into boxes
  • Coin change with unlimited coins (counting)
  • Allocating resources
  • Non-negative integer solutions: x₁ + x₂ + ... + xₖ = n

Example:

  • Distribute 5 apples into 3 baskets = C(5+3-1, 3-1) = C(7, 2) = 21 ways

Problems:


5. Derangements

"Permutations where no element is in its original position"

Formula: D(n) = (n-1) × (D(n-1) + D(n-2))

Use Cases:

  • Secret Santa (everyone gets someone else's name)
  • Hat check problem
  • Round-robin tournaments
  • Matching problems with constraints

Example:

  • D(3) = 2: [2,3,1], [3,1,2]
  • D(4) = 9

Sequence: 0, 1, 2, 9, 44, 265...


6. Modular Arithmetic

Modular Inverse

When to use: Division in modular arithmetic (mod operations).

Formula: a⁻¹ ≡ a^(MOD-2) (mod MOD) (Fermat's Little Theorem, MOD is prime)

Use Case: Computing nCr with large values under modulo

  • Instead of: (a / b) % MOD (WRONG)
  • Use: (a × inverse(b)) % MOD (CORRECT)

Modular Exponentiation

Fast power calculation: Compute a^b % MOD in O(log b)

Use Cases:

  • Large power calculations
  • RSA cryptography basics
  • Matrix exponentiation for DP

Common Interview Patterns

Pattern 1: Grid Paths

Problem: Count paths in m×n grid (only right/down moves)

Solution: C(m+n-2, m-1) or C(m+n-2, n-1)

Why? Total moves = (m-1) down + (n-1) right. Choose positions for down moves.

Problems:


Pattern 2: Subset Selection

Problem: Choose k items from n items

Solution: C(n, k)

Problems:


Pattern 3: Counting BSTs

Problem: Count structurally unique BSTs with n nodes

Solution: Catalan(n)

Problems:


Pattern 4: Valid Parentheses

Problem: Count valid parentheses combinations with n pairs

Solution: Catalan(n)

Problems:


Pattern 5: Stair Climbing Variants

Problem: Climb n stairs with [1, 2, 3, ...] steps allowed

Solution:

  • 1 or 2 steps → Fibonacci
  • General case → DP or combinatorics

Problems:


Usage Tips

When to Precompute

✅ Use precomputation when:

  • Multiple queries (Q > 100)
  • Max n ≤ 10^6
  • Time limit is tight

❌ Don't precompute when:

  • Single query
  • n is very large (> 10^7)
  • Space is limited

Choosing nCrDirect vs nCr

  • nCrDirect: Small n, no modulo needed (n ≤ 20)
  • nCr (precomputed): Multiple queries, needs modulo, n ≤ 10^6

Common Pitfalls

  1. Overflow: Use long for intermediate calculations
  2. Division in mod: Use modular inverse, not direct division
  3. Range: Ensure n doesn't exceed precomputed range
  4. Edge cases: C(n, 0) = 1, C(n, n) = 1, C(n, r) = 0 if r > n

Practice Problems

Beginner

Intermediate

Advanced


Complexity Analysis

Precomputation: O(n) Space: O(n) Query (nCr, nPr, factorial): O(1) Modular operations: O(log MOD)

Memory: ~24n bytes (3 arrays of size n)


Quick Code Snippet for CP

// Initialize once
Combinatorics comb = new Combinatorics(100000);

// Fast queries
long ways = comb.nCr(n, k);  // O(1)
long arrangements = comb.nPr(n, k);  // O(1)
long bsts = comb.catalan(n);  // O(1)

Note: All operations use MOD = 10^9 + 7 by default (common in competitive programming).