Combinatorics
ℹ️ Why It Matters
Combinatorics is the mathematics of counting, arranging, and structuring discrete objects. It underpins algorithm analysis, probability theory, cryptography, and complexity theory. From determining the number of possible passwords to analyzing the worst-case runtime of sorting algorithms, combinatorics provides the essential tools for quantifying discrete possibilities. Every time you wonder "how many ways can this happen?", you are doing combinatorics.
Counting Principles
ThProduct Rule (Multiplication Principle)
If a task consists of independent stages, where stage has possible outcomes, then the total number of outcomes for the entire task is:
Example: A license plate has 2 letters followed by 4 digits. There are possible plates.
ThSum Rule (Addition Principle)
If a task can be performed in one of ways OR in one of ways, and the two sets of ways are disjoint (mutually exclusive), then the total number of ways is:
More generally, if a task can be done in mutually exclusive ways, the total is .
Example: A student can choose from 5 math courses OR 3 CS courses OR 2 physics courses. Total options: .
⚠️ When to Apply Each Rule
- Product Rule: Multiple stages that happen together (AND). "Do this AND then that."
- Sum Rule: Multiple alternatives (OR). "Do this OR that."
- If unsure, ask: "Do I need to complete all stages, or just one of several options?"
Permutations
Permutations (Ordered Arrangements)
Here,
- =Total number of distinct items
- =Number of items to arrange
- =Number of ordered arrangements of k items from n
📝Example: Arranging Books
How many ways can you arrange 3 books chosen from a shelf of 8?
ℹ️ Full Permutations
When , we get , the total number of ways to arrange all items. For example, .
Combinations
Combinations (Unordered Selections)
Here,
- =Total number of distinct items
- =Number of items to choose
- =Number of ways to choose k items from n (order does not matter)
📝Example: Choosing a Committee
A committee of 4 people is to be chosen from a group of 12.
⚠️ Permutation vs. Combination
Use permutations when order matters (e.g., assigning ranks: 1st, 2nd, 3rd). Use combinations when order does not matter (e.g., selecting a group of members).
The relationship between them:
Permutations with Repetition
Permutations with Repetition
Here,
- =Number of distinct items to choose from
- =Number of positions to fill (repetition allowed)
📝Example: Binary Strings
How many 8-bit binary strings are possible? Each bit can be 0 or 1 (repetition allowed).
📝Example: Password with Repetition
A 4-character password using 26 lowercase letters (repetition allowed):
Combinations with Repetition
Combinations with Repetition (Stars and Bars)
Here,
- =Number of distinct types of items
- =Number of items to select (repetition allowed)
📝Example: Distributing Candies
You have 3 types of candy and want to choose 5 pieces (repetition allowed).
ℹ️ Stars and Bars Visualization
To distribute identical items into distinct bins, we use bars to separate bins and stars to represent items. The total arrangements of stars and bars is .
Binomial Theorem
ThBinomial Theorem
For any real numbers and and non-negative integer :
The binomial coefficient gives the coefficient of the term.
Binomial Expansion
Here,
- =Binomial coefficient (appears as the coefficient of each term)
- =Terms being raised to the power n
📝Example: Expanding (x + y)^3
📝Example: Binomial Coefficients Sum
What is ?
Setting in the Binomial Theorem:
Pascal's Triangle
DfPascal's Triangle
Pascal's Triangle is a triangular array where each entry is the sum of the two entries directly above it. Row (starting from ) contains the binomial coefficients .
First 8 rows of Pascal's Triangle:
Row 0: 1
Row 1: 1 1
Row 2: 1 2 1
Row 3: 1 3 3 1
Row 4: 1 4 6 4 1
Row 5: 1 5 10 10 5 1
Row 6: 1 6 15 20 15 6 1
Row 7: 1 7 21 35 35 21 7 1
ThPascal's Identity
Each entry is the sum of the two entries above it.
ℹ️ Properties of Pascal's Triangle
- Symmetry:
- Sum of row :
- Hockey stick identity:
- Fibonacci numbers appear along shallow diagonals.
Inclusion-Exclusion Principle
Inclusion-Exclusion (Two Sets)
Here,
- =Size of set A
- =Size of set B
- =Size of the intersection of A and B
Inclusion-Exclusion (Three Sets)
Here,
- =Size of the union of three sets
General Inclusion-Exclusion
Here,
- =Sets to be combined
- =Index subset of {1, 2, ..., n}
📝Example: Survey Problem
In a survey of 100 people: 60 like tea, 50 like coffee, 40 like both. How many like at least one?
ℹ️ When to Use Inclusion-Exclusion
Use inclusion-exclusion when counting the union of overlapping sets. It corrects for double-counting elements that belong to multiple sets.
Pigeonhole Principle
ThPigeonhole Principle (Basic)
If items are placed into containers and , then at least one container contains more than one item.
ThPigeonhole Principle (Generalized)
If items are placed into containers, then at least one container contains at least items.
📝Example: Birthday Problem
In a group of 367 people, at least two people must share a birthday (since there are only 366 possible birthdays including Feb 29).
📝Example: Socks in a Drawer
A drawer contains 10 black socks and 10 blue socks. How many must you pull out (in the dark) to guarantee a matching pair?
Using the pigeonhole principle with 2 colors: you need to pull out socks. The first two might not match, but the third must match one of the first two.
ℹ️ Pigeonhole in Competitions
The pigeonhole principle is a favorite in math competitions and coding interviews because it provides elegant non-constructive proofs�proving something exists without finding it explicitly.
Python Implementation
from math import comb, perm, factorial
from itertools import combinations, permutations
from functools import reduce
import operator
# Basic calculations
print(f"10! = {factorial(10)}") # 3628800
print(f"P(10,3) = {perm(10, 3)}") # 720
print(f"C(10,3) = {comb(10, 3)}") # 120
# Pascal's Triangle
def pascal_triangle(n):
triangle = [[1]]
for i in range(1, n + 1):
row = [1]
for j in range(1, i):
row.append(triangle[i-1][j-1] + triangle[i-1][j])
row.append(1)
triangle.append(row)
return triangle
for row in pascal_triangle(7):
print(" " * (7 - len(row)) + " ".join(map(str, row)))
# Inclusion-Exclusion for two sets
def inclusion_exclusion_two(A, B, A_inter_B):
return A + B - A_inter_B
# Example: people who like tea or coffee
tea, coffee, both = 60, 50, 40
print(f"At least one: {inclusion_exclusion_two(tea, coffee, both)}") # 70
# Pigeonhole principle
def min_pigeonhole(items, containers):
import math
return math.ceil(items / containers)
print(f"Min in one container (17 items, 5 boxes): {min_pigeonhole(17, 5)}") # 4
# Combinations with repetition
def comb_repetition(n, k):
return comb(n + k - 1, k)
print(f"C(3,5) with repetition: {comb_repetition(3, 5)}") # 21
# Generating all combinations
items = ['A', 'B', 'C', 'D']
print("Combinations of 2 from ABCD:")
for c in combinations(items, 2):
print(f" {c}")
Applications in AI/ML
ℹ️ Combinatorics in AI and Machine Learning
Combinatorial reasoning is fundamental to many AI and ML concepts:
Hyperparameter Search
The number of hyperparameter configurations grows combinatorially. If a model has 4 hyperparameters with 5, 10, 3, and 7 possible values respectively, a grid search requires evaluations.
Feature Selection
Selecting the best features from candidates is a combinatorial problem with possibilities. For features and , this is approximately combinations�too many to brute-force.
Permutation Tests
Permutation tests in statistics compare observed statistics against distributions generated by randomly permuting labels. The total number of permutations is , making exact tests infeasible for large .
Neural Architecture Search
NAS explores architectures as combinations of layers, connections, and operations. The search space grows exponentially with depth and breadth.
Attention Mechanisms
Self-attention in Transformers considers all pairs of positions, leading to complexity. Understanding this combinatorial structure drives efficient attention variants.
Common Mistakes
| Mistake | Correct Approach | Example |
|---|---|---|
| Using permutations when order doesn't matter | Use combinations for unordered selections | Choosing a committee: use , not |
| Forgetting to divide by | Combinations divide out the ordering: | |
| Adding when you should multiply | Use product rule for sequential stages | 3 shirts AND 2 pants = outfits |
| Multiplying when you should add | Use sum rule for alternative choices | 3 shirts OR 2 pants = choices |
| Ignoring overlapping sets | Apply inclusion-exclusion | |
| Confusing repetition formulas | is ordered repetition; is unordered | Passwords: ; candy selection: stars and bars |
Interview Questions
-
How many ways can you arrange the letters in "MISSISSIPPI"?
Answer:
-
If you flip a coin 10 times, how many outcomes have exactly 7 heads?
Answer:
-
You have 5 different books. How many ways can you arrange them on a shelf such that two specific books are always adjacent?
Answer: Treat the two books as one unit.
-
What is the coefficient of in ?
Answer:
-
How many 5-digit numbers use only the digits {1, 2, 3} and each digit appears at least once?
Answer: (inclusion-exclusion)
-
Given 12 people, how many ways to form a committee of 5 with a designated chair?
Answer: Choose 5 from 12, then choose chair from 5:
Practice Problems
📝Practice 1: Password Strength
How many 8-character passwords can be formed using 26 lowercase letters, 10 digits, and 10 special characters if repetition is allowed?
💡Solution 1
Total characters: . With repetition: .
📝Practice 2: Distributing Gifts
In how many ways can 12 identical gifts be distributed among 4 children?
💡Solution 2
Stars and bars: .
📝Practice 3: Derangements
A derangement is a permutation where no element appears in its original position. How many derangements of exist?
💡Solution 3
Using inclusion-exclusion: .
📝Practice 4: Counting Paths
On a 5�5 grid, how many shortest paths exist from the bottom-left to the top-right corner (only moving right or up)?
💡Solution 4
You must make exactly 5 right moves and 5 up moves (10 total). The number of paths is .
Quick Reference
| Formula | Name | When to Use |
|---|---|---|
| Factorial | Arranging all items | |
| Permutations | Choosing and arranging from | |
| Combinations | Choosing from (unordered) | |
| Permutations with Repetition | Filling slots from options | |
| Combinations with Repetition | Choosing from with replacement | |
| Inclusion-Exclusion | Overlapping sets | |
| Pigeonhole (generalized) | Minimum items in one container | |
| Pascal's Identity | Recursive binomial computation |
Cross-References
- Probability Theory: Combinatorics provides the sample space counting for classical probability calculations.
- Discrete Probability Distributions — The binomial distribution uses .
- Graph Theory: Counting edges, paths, cycles, and spanning trees all rely on combinatorial methods.
- Algorithm Analysis: The number of subsets , permutations , and combinations appear in time complexity analysis.
- Information Theory — Combinatorial entropy bounds relate to the number of possible messages.
- Cryptography: Key space size is , computed via combinatorial counting.
Summary
📋Key Takeaways
-
Product and Sum Rules: The product rule counts ordered pairs from sequential stages, while the sum rule counts disjoint alternatives. These are the two pillars of all counting.
-
Permutations vs. Combinations: Permutations count ordered arrangements, while combinations count unordered selections. Order matters for permutations, not for combinations.
-
Repetition Variants: With repetition, ordered selections give possibilities, while unordered selections give via stars and bars.
-
Binomial Theorem: connects combinations to algebra. The coefficients appear in Pascal's triangle.
-
Pascal's Identity: enables efficient recursive computation of binomial coefficients.
-
Inclusion-Exclusion: Corrects for double-counting in overlapping sets. For two sets: .
-
Pigeonhole Principle: If , at least one of containers holds more than one item. Generalized: at least one holds items.
-
Factorials Grow Fast: grows extremely rapidly � . This is why approximation methods like Stirling's formula are useful.
-
AI/ML Applications: Combinatorial explosion drives the need for heuristics in hyperparameter search, feature selection, and neural architecture search.