Permutations & Combinations Roadmap

Counting from the very first idea to interview-level problems: 20 topics in four stages, each with what to learn, a worked example, free resources, something to build and easy, medium and hard LeetCode problems, 60 in all (every one free). Start with the animations just below: they show what a permutation and a combination are and exactly how they differ.

Start here: permutations vs combinations in two minutes

Both answer "how many ways can I pick k things from n?". The only question that separates them is: does the order of the picked things matter?

Permutation = an arrangement

Order matters. A, B, C in that order is a different result from C, B, A.

Gold–silver–bronze, a password, a seating plan, a playlist order.

P(n, k) = n! / (n − k)!

Pick 2 of A, B, C, D in order: 4 × 3 = 12 (AB, BA, AC, CA, …)

Combination = a selection

Order doesn't matter. {A, B, C} is the same group as {C, B, A}.

A team, a committee, pizza toppings, lottery numbers, a hand of cards.

C(n, k) = n! / (k! · (n − k)!)

Pick 2 of A, B, C, D as a group: 12 ÷ 2 = 6 (AB, AC, AD, BC, BD, CD)

Animation 1: arrange vs choose

Press Play. Every ordered pick is a new permutation (left). On the right, orderings of the same letters collapse into one combination, and the counter shows how many orderings each group absorbed.

Animation 2: which formula do I need?

Answer two questions (does order matter? can an item repeat?) or click a box. You get the formula, a real-life example and every single outcome listed.

PermutationCombination
Order matters?Yes: AB ≠ BANo: AB = BA
Words in the questionarrange, order, rank, line up, schedule, password, first/second/thirdchoose, select, pick, group, team, committee, subset, hand
Formula (no repeats)P(n, k) = n! / (n − k)!C(n, k) = n! / (k! (n − k)!)
With repeats allowednᵏC(n + k − 1, k) (stars and bars)
n = 5, k = 36010
How they relateP(n, k) = C(n, k) × k!: choose the group first, then arrange its k items in k! ways.

Two more animations live inside the roadmap: the backtracking tree that generates them in code and Pascal's triangle.

The roadmap in detail

Everything from the map above, on one page. Dashed topics are optional. The hours are rough estimates for reading, working the examples by hand and solving the problems.

Stage 1 · Beginner Counting basics

Two rules, one symbol (the factorial) and two formulas. By the end of this stage you can look at a counting question, decide whether it's a permutation or a combination, and get the number.

The sum rule and the product rule

Almost all counting is built from two rules. Sum rule (OR): if a choice can be made in one of several separate ways, add them. 3 trains or 2 buses to work = 3 + 2 = 5 ways. Product rule (AND): if a task is a sequence of independent steps, multiply. 3 shirts and 4 trousers = 3 × 4 = 12 outfits. A 4-digit PIN is 10 × 10 × 10 × 10 = 10,000 codes.

The third trick is counting the complement: when "at least one" is hard, count everything and subtract the bad cases. PINs with at least one repeated digit = all PINs − PINs with all different digits = 10,000 − 10 × 9 × 8 × 7 = 4,960.

What to learn

  • The sum rule: separate, non-overlapping cases add up
  • The product rule: independent steps in a row multiply
  • Drawing a small tree diagram to check a product
  • Complement counting: total minus the cases you don't want
  • Brute-force counting in code to check your formula on small inputs

Free resources

Practice problems

Build it yourself

Write a function that counts licence plates of the form 3 letters + 3 digits with the product rule, then count by brute force with nested loops and check the two numbers match (17,576,000). Then count plates with at least one repeated letter using the complement.

Factorials: arranging everything

n! ("n factorial") is n × (n − 1) × … × 2 × 1: the number of ways to put n different things in a row. The first position has n choices, the next n − 1, and so on (that's the product rule). 3! = 6 (ABC, ACB, BAC, BCA, CAB, CBA), 5! = 120, 10! = 3,628,800. By definition 0! = 1: there is exactly one way to arrange nothing.

Factorials grow faster than any exponential: 20! already needs 64 bits and 21! overflows a 64-bit integer. That's why counting answers in code are usually asked "modulo 10⁹ + 7" (stage 4) and why trying all n! orderings only works for n up to about 10.

What to learn

  • Why n things can be ordered in n! ways
  • Why 0! = 1
  • Cancelling factorials: 7! / 5! = 7 × 6 = 42 without computing either
  • How fast n! grows and where it overflows 32-bit and 64-bit integers

Free resources

Practice problems

Build it yourself

Print n! for n = 0 to 25 using 32-bit ints, 64-bit ints and big integers side by side, and note the first n where each one goes wrong.

Permutations: P(n, k)

A permutation is an ordered arrangement. Arranging only k of the n items: the first slot has n choices, the second n − 1, …, the k-th has n − k + 1, so P(n, k) = n × (n − 1) × … × (n − k + 1) = n! / (n − k)!. It's also written ⁿPₖ or nPr.

Worked example: 8 runners, how many ways to award gold, silver and bronze? 8 × 7 × 6 = 336 = 8! / 5!. Arranging all n is the special case k = n: P(n, n) = n!.

What to learn

  • Deriving P(n, k) from the product rule, slot by slot
  • Writing it with factorials and computing it without overflow (multiply only k terms)
  • Arrangements with conditions: "A must be first", "A and B together" (glue them into one block), "A and B apart" (total − together)
  • Listing all P(4, 2) = 12 by hand to see the pattern

Free resources

Practice problems

Build it yourself

Write nPr(n, k) that multiplies only k terms, test it against factorial(n) / factorial(n - k) for all n ≤ 15, and count the seatings of 6 friends in a row where two of them refuse to sit next to each other (answer: 480).

Combinations: C(n, k)

A combination is an unordered selection. Start from the P(n, k) ordered picks: each group of k items was counted once for every way of ordering it, which is k! times. Divide that out: C(n, k) = P(n, k) / k! = n! / (k! (n − k)!). It's read "n choose k" and also written ⁿCₖ, nCr or as a binomial coefficient.

Worked example: a team of 3 from 8 people: 336 ordered picks ÷ 3! = 56 teams. Useful facts: C(n, 0) = C(n, n) = 1, and C(n, k) = C(n, n − k) (choosing who's in is the same as choosing who's out). Counting pairs is C(n, 2) = n(n − 1)/2, which shows up everywhere: handshakes, matches in a league, equal pairs in an array.

What to learn

  • Why dividing by k! removes the orderings
  • The symmetry C(n, k) = C(n, n − k)
  • C(n, 2) = n(n − 1)/2 for counting pairs, and grouping equal values with a hash map
  • Computing C(n, k) safely: multiply and divide step by step (result stays an integer at every step)
  • Mixed questions: "a committee of 2 men and 3 women" = C(men, 2) × C(women, 3)

Free resources

Practice problems

Build it yourself

Write nCr(n, k) using the loop r = r * (n - i) / (i + 1) with k replaced by min(k, n − k), and check C(52, 5) = 2,598,960 (poker hands) and C(49, 6) = 13,983,816 (a 6/49 lottery).

Permutation or combination? Telling them apart

Ask one question: if I swap two of the chosen items, do I get a different answer? If yes, order matters: permutation. If no: combination. Picking a president and a vice-president from 10 people is P(10, 2) = 90 (Ana–Ben differs from Ben–Ana). Picking 2 people for a committee is C(10, 2) = 45. Then ask a second question: can the same item be picked again? That gives the four cases in Animation 2 at the top of the page.

Watch out for the everyday word "combination lock": the order of the digits matters, so it's really a permutation lock (with repetition, nᵏ). Many problems mix both: "choose 3 of 7 books and arrange them on a shelf" = C(7, 3) × 3! = P(7, 3) = 210.

What to learn

  • The swap test: does reordering the picks change the outcome?
  • The repetition test: can an item be used more than once?
  • Keyword cues (arrange, rank, order vs choose, select, group) and why they can mislead
  • P(n, k) = C(n, k) × k!: choose first, arrange second
  • Mixed problems that choose some items, then order them

Free resources

Practice problems

Build it yourself

Write 10 counting questions from real life (a playlist, a pizza order, a football league, a bike lock, a hand of cards…), label each one permutation or combination and with or without repetition, solve it, then check your labels in Animation 2.

Tools on this site

Am I ready? Stage 1 quiz

You have 4 shirts and 3 pairs of shoes. How many outfits of one shirt and one pair of shoes?

  1. 7
  2. 12
  3. 24
  4. 81

Two independent steps, so multiply: 4 × 3 = 12 (product rule).

How many ways can 5 books be arranged in a row on a shelf?

  1. 5
  2. 25
  3. 120
  4. 3,125

All 5 are arranged and order matters: 5! = 120.

A club of 10 elects a president, a secretary and a treasurer. Which formula?

  1. P(10, 3) = 720
  2. C(10, 3) = 120
  3. 10³ = 1,000
  4. 3! = 6

The roles are different, so swapping two people gives a different result: order matters, no repeats.

How many different 3-person teams can be picked from 10 people?

  1. 30
  2. 720
  3. 1,000
  4. 120

A team has no order: C(10, 3) = 720 / 3! = 120.

What is the relationship between P(n, k) and C(n, k)?

  1. They're always equal
  2. P(n, k) = C(n, k) × k!
  3. C(n, k) = P(n, k) × k!
  4. P(n, k) = C(n, k) + k

Each unordered group of k items can be ordered in k! ways, so the ordered count is k! times bigger.

Stage 2 · Intermediate Repetition, identities and subsets

Real problems allow repeats, have identical items, or ask about every possible subset. This stage covers those cases and the identities (Pascal's rule, the binomial theorem) that let you compute combinations fast.

Repetition: nᵏ, identical items and stars and bars

Three cases come up again and again. Ordered with repetition: each of k slots can be any of n items, so nᵏ (a 4-digit PIN: 10⁴). Arranging items that repeat (a multiset): arrange as if all were different, then divide by the orderings of each identical group: the letters of MISSISSIPPI give 11! / (1! 4! 4! 2!) = 34,650 words. Unordered with repetition: choose k items from n kinds, repeats allowed (3 scoops from 5 ice cream flavours). Picture the k scoops as stars and the n − 1 dividers between flavours as bars: any row of k stars and n − 1 bars is one choice, so the answer is C(n + k − 1, k) = C(7, 3) = 35.

Stars and bars also counts how many ways to split k identical things into n groups: 10 identical sweets among 3 children is C(12, 2) = 66, or C(9, 2) = 36 if every child must get at least one.

What to learn

  • nᵏ for ordered picks with repetition
  • Multiset permutations: n! / (a! b! c! …)
  • Stars and bars: C(n + k − 1, k), and the "at least one each" version C(k − 1, n − 1)
  • Recognising which of the four cases (order? repetition?) a problem is

Free resources

Practice problems

Build it yourself

Solve 1641 three ways: brute force over all strings, a DP table, and the one-line formula C(n + 4, 4). Then count the distinct arrangements of the letters of your own name.

Tools on this site

Pascal's triangle and the binomial theorem

Write 1 at the top; each number below is the sum of the two above it. Row n, position k (both counted from 0) is exactly C(n, k). That's Pascal's rule: C(n, k) = C(n − 1, k − 1) + C(n − 1, k). Why? Look at one particular item: either it's in your group (choose the other k − 1 from n − 1) or it isn't (choose all k from the other n − 1).

The same numbers are the coefficients in (a + b)ⁿ: (a + b)³ = a³ + 3a²b + 3ab² + b³, coefficients 1 3 3 1 (the binomial theorem). Each row adds up to 2ⁿ, the number of subsets. In code, Pascal's rule builds a table of every C(n, k) with additions only, no division and no overflow until the numbers themselves get big.

Animation 3: Pascal's triangle

Click any number to see the two numbers it's built from and what it counts. Press "Build it" to watch the triangle grow row by row.

What to learn

  • Pascal's rule and the "is this item in or out?" proof
  • Building a C(n, k) table with DP in O(n²) time
  • The binomial theorem and the coefficients of (a + b)ⁿ
  • Row sums are 2ⁿ; the triangle is symmetric because C(n, k) = C(n, n − k)
  • The hockey-stick identity (a diagonal sum equals the number below its end)

Free resources

Practice problems

Build it yourself

Build Pascal's triangle up to row 30 with one array updated right to left (O(n) memory), compare a few values with your nCr from stage 1, and print the triangle with odd numbers as # and even as a space to discover the Sierpiński triangle.

Subsets and the power set: 2ⁿ

For each of n items you decide "in" or "out", two choices n times, so a set of n items has 2ⁿ subsets (including the empty set and the full set). Grouping them by size gives C(n, 0) + C(n, 1) + … + C(n, n) = 2ⁿ, a row of Pascal's triangle.

In code, the in/out choices are the bits of a number: every integer from 0 to 2ⁿ − 1 is one subset (bitmask enumeration). For [a, b, c], mask 101 in binary = {a, c}. This is the simplest way to try every subset when n ≤ 20.

What to learn

  • Why there are 2ⁿ subsets, and the sum of a Pascal row
  • Bitmask enumeration: for mask in 0 .. 2ⁿ − 1, test bit i with mask >> i & 1
  • Counting subsets with a property (each element contributes to 2ⁿ⁻¹ subsets)
  • When 2ⁿ is too big (n > ~25) and you need DP or meet-in-the-middle instead

Free resources

Practice problems

Build it yourself

Print every subset of [a, b, c, d] with a bitmask loop next to its binary mask, then solve 1863 twice: once by trying all subsets, once in O(n) using the fact that each set bit appears in 2ⁿ⁻¹ subsets.

Tools on this site

Circular arrangements and restrictions

Around a round table there's no "first seat": rotating everyone gives the same seating. Fix one person and arrange the rest: (n − 1)! ways. If the circle can also be flipped (a necklace or a key ring), divide by 2 more: (n − 1)! / 2. Common restrictions: "these two sit together" (glue them into one block, then × 2 for their inner order) and "no two of these are adjacent" (seat the others first, then choose gaps for the restricted ones: the gap method).

What to learn

  • Circular permutations (n − 1)! and why rotations are the same
  • Necklaces and bracelets: when to divide by 2 as well
  • The block method for "must be together"
  • The gap method for "must not be next to each other"

Free resources

Build it yourself

Count the seatings of 6 people at a round table where two particular people must sit together (answer: 48), and confirm it by generating all 720 straight-line orderings and grouping them by rotation.

Am I ready? Stage 2 quiz

How many 4-digit PINs are there if digits can repeat?

  1. 5,040
  2. 210
  3. 10,000
  4. 24

Ordered, repeats allowed: 10⁴ = 10,000.

How many distinct arrangements of the letters in BANANA?

  1. 60
  2. 720
  3. 120
  4. 20

6! / (3! for the A's × 2! for the N's) = 720 / 12 = 60.

You pick 3 scoops from 4 flavours, repeats allowed, order in the cup doesn't matter. How many choices?

  1. 64
  2. 4
  3. 24
  4. 20

Unordered with repetition is stars and bars: C(4 + 3 − 1, 3) = C(6, 3) = 20.

Which number is directly below 4 and 6 in Pascal's triangle?

  1. 24
  2. 10
  3. 12
  4. 5

Each number is the sum of the two above: 4 + 6 = 10, which is C(5, 2).

How many subsets does a set of 10 elements have?

  1. 10
  2. 100
  3. 1,024
  4. 3,628,800

Each element is in or out: 2¹⁰ = 1,024, including the empty set.

Stage 3 · Intermediate Generating them in code

Counting tells you how many; interviews often ask you to list them all. One recursive pattern, backtracking, generates subsets, combinations and permutations with only small changes. The decision tree animation below shows exactly how.

The backtracking template

Backtracking builds an answer one choice at a time: choose an item, explore (recurse), then un-choose it and try the next. The calls form a decision tree: the root is the empty choice and every path from the root is a partial answer. The three generators differ only in two lines: when you record the path and which items you may pick next.

  • Subsets: record at every node; next items start after the last pick (i + 1).
  • Combinations: record only when the path has k items; next items start after the last pick.
  • Permutations: record when the path has all n items; any item not used yet may come next (a used[] array).

Animation 4: the backtracking tree

Pick a mode and press Play or Step. The blue node is where the recursion is now, the highlighted line is the code running, and green nodes are recorded answers.

What to learn

  • The choose → explore → un-choose shape and why the un-choose step matters
  • Copying the path when you record it (not storing the same list over and over)
  • Reading the recursion as a tree: depth = path length, leaves = answers
  • Time complexity: the number of answers × the cost of copying each one
  • Pruning: stopping a branch early when it can't lead to an answer

Free resources

Practice problems

Build it yourself

Write one function backtrack(mode, nums, k) that produces subsets, k-combinations or permutations depending on mode, and check the counts are 2ⁿ, C(n, k) and n!.

Tools on this site

Generating subsets

Three equivalent ways: (1) backtracking, recording the path at every node; (2) include/exclude recursion, where each level decides "take nums[i] or skip it" and the leaves are the subsets; (3) bitmasks, one subset per number from 0 to 2ⁿ − 1. With duplicates in the input ([1, 2, 2]), sort first and, at the same tree level, skip a value equal to the previous one (if i > start and nums[i] == nums[i-1]: continue) so [1, 2] isn't produced twice.

What to learn

  • Subsets with backtracking (record at every node)
  • Subsets with include/exclude recursion
  • Subsets with a bitmask loop
  • Sort + skip equal neighbours at the same level to remove duplicates

Free resources

Practice problems

Build it yourself

Solve 78 all three ways and check they give the same set of subsets (sort each subset and the list before comparing). Then solve 90 and confirm [1, 2, 2] gives 6 subsets, not 8.

Generating combinations

Same tree as subsets, but you record only when the path has exactly k items, and you can prune: if there aren't enough items left to reach k, stop (loop only while i ≤ n − (k − path.length)). Variants: reuse allowed (Combination Sum: recurse with i instead of i + 1), each item once with duplicates (Combination Sum II: sort and skip equal neighbours), and a target sum (stop when the running sum passes the target, which on a sorted array prunes the rest of the loop too).

What to learn

  • k-combinations with a start index
  • The "not enough items left" pruning
  • Allowing reuse by recursing with i instead of i + 1
  • Target-sum pruning on a sorted array

Free resources

Practice problems

Build it yourself

Solve 77 for n = 20, k = 10 with and without the pruning and count the recursive calls in each version. The number of answers is the same (184,756); the number of calls is not.

Generating permutations

Use a used[] array: at each level try every item not used yet, mark it, recurse, unmark. The tree has n! leaves. An alternative is swapping in place: at level i, swap each later element into position i, recurse on i + 1, swap back. With duplicate values, sort and skip an item if it equals the previous one and the previous one is not currently used, which keeps the n! / (repeats) count from stage 2. Constraints ("adjacent numbers must sum to a square", "no two queens attack") turn this into a search with pruning.

What to learn

  • Permutations with a used[] array
  • Permutations by swapping in place
  • Skipping duplicates: sort + the "previous equal and unused" rule
  • Pruning with constraints while building the permutation
  • Heap's algorithm (each permutation differs from the last by one swap), for interest

Free resources

Practice problems

Build it yourself

Write both the used[] and the swap versions of 46, then 47, and check [1, 1, 2, 2] gives 4! / (2! 2!) = 6 permutations.

Lexicographic order: next and k-th permutation

Sorted like words in a dictionary, the permutations of 1 2 3 are 123, 132, 213, 231, 312, 321. To get the next permutation in place: from the right, find the first i with a[i] < a[i + 1]; swap a[i] with the smallest element to its right that's bigger than it; reverse everything after i. It's O(n) and is what C++'s std::next_permutation does. To jump straight to the k-th permutation without listing the others, use the factorial number system: (k − 1) ÷ (n − 1)! tells you which item goes first, the remainder ÷ (n − 2)! gives the second, and so on.

What to learn

  • Lexicographic order of permutations
  • The next-permutation algorithm (find pivot, swap, reverse the suffix)
  • Finding the k-th permutation with the factorial number system
  • The reverse: the rank of a permutation (the Lehmer code)

Free resources

Practice problems

Build it yourself

Starting from the sorted array, call your next-permutation function until it wraps around and check you got all n! permutations in order. Then write kth(n, k) and check kth(4, 9) = 2314.

Am I ready? Stage 3 quiz

What are the three steps of the backtracking pattern?

  1. Sort, search, return
  2. Choose, explore, un-choose
  3. Divide, conquer, combine
  4. Push, pop, peek

You make a choice, recurse, then undo the choice so the next option starts from a clean state.

In the backtracking tree for subsets, which nodes are answers?

  1. Only the leaves
  2. Only nodes at depth k
  3. Only the root
  4. Every node, including the root (the empty set)

Every path from the root is a valid subset, so subsets are recorded at every node: 2ⁿ of them.

Combination Sum lets you reuse a number. What changes in the code?

  1. Recurse with i instead of i + 1
  2. Remove the base case
  3. Use a used[] array
  4. Sort in descending order

Starting the next level at i again allows the same number to be picked repeatedly, while still never going backwards (so no duplicate orderings).

What is the next permutation after 1 3 2?

  1. 1 2 3
  2. 3 2 1
  3. 2 1 3
  4. 3 1 2

Pivot is 1 (first from the right smaller than its neighbour); swap with 2 (smallest bigger to its right) giving 2 3 1, then reverse the suffix: 2 1 3.

How do you avoid duplicate results when generating subsets of [1, 2, 2]?

  1. Store results in a set of strings after generating everything
  2. Sort, then skip a value equal to the previous one at the same tree level
  3. Remove duplicates from the input first
  4. It's impossible without a hash set

Sorting puts equal values together, and skipping repeats at the same level stops the same subset being built twice. (A set works but wastes time; removing duplicates from the input loses [2, 2].)

Stage 4 · Advanced Counting at interview scale

When n is 10⁵, you can't list anything: you need the formula, computed modulo a prime. This stage adds modular arithmetic, the classic counting families (grid paths, Catalan numbers) and the tricks for overlapping cases.

Computing nCr modulo 10⁹ + 7

Answers get astronomically big, so problems ask for them modulo a prime p, usually 10⁹ + 7. Addition and multiplication work fine modulo p, but division doesn't: instead of dividing by x, multiply by its modular inverse. Because p is prime, Fermat's little theorem gives x⁻¹ = x^(p − 2) mod p, computed with fast exponentiation in O(log p). The standard recipe: precompute fact[i] and invFact[i] up to the largest n once, then every C(n, k) = fact[n] × invFact[k] × invFact[n − k] mod p in O(1). For small n (≤ ~5,000) a Pascal's triangle table with additions mod p also works.

What to learn

  • Why answers are given modulo 10⁹ + 7 and how to avoid overflow in a × b mod p
  • Fast exponentiation (binary exponentiation)
  • Modular inverse with Fermat's little theorem
  • Precomputed factorials and inverse factorials for O(1) nCr
  • The Pascal table alternative for small n, and Lucas's theorem when p is small (optional)

Free resources

Practice problems

Build it yourself

Write a small combinatorics helper (power, inverse, fact, invFact, nCr, nPr) that you can paste into any solution, and test it against exact big-integer results for n ≤ 60.

Tools on this site

Grid paths: combinations in disguise

To walk from the top-left to the bottom-right of an m × n grid moving only right or down, you make exactly (m − 1) downs and (n − 1) rights in some order. A path is fully decided by which of the m + n − 2 moves are downs, so there are C(m + n − 2, m − 1) paths. A 3 × 7 grid has C(8, 2) = 28. With blocked cells the formula breaks and you count with DP instead (paths to a cell = paths from above + paths from the left), which is Pascal's rule turned sideways.

What to learn

  • Turning a path into a sequence of moves and choosing positions
  • The formula C(m + n − 2, m − 1) and computing it without overflow
  • DP for grids with obstacles
  • Paths through a required point = paths to it × paths from it

Free resources

Practice problems

Build it yourself

Solve 62 with the formula and with DP and compare for every grid up to 15 × 15. Then count paths in a 10 × 10 grid that must pass through cell (4, 6).

Catalan numbers

1, 1, 2, 5, 14, 42, 132, … The n-th Catalan number Cₙ = C(2n, n) / (n + 1) counts a surprising number of things: valid strings of n pairs of brackets, binary search trees with n keys, ways to triangulate a polygon, and grid paths that never cross the diagonal. The recurrence Cₙ = Σ Cᵢ × Cₙ₋₁₋ᵢ comes from splitting at the first matching bracket (or the root of the tree): an inside part and an outside part.

What to learn

  • The formula C(2n, n) / (n + 1) and the first ten values
  • The recurrence and why "split at the root / first bracket" gives it
  • Recognising Catalan problems: brackets, BSTs, non-crossing structures
  • Generating all valid bracket strings with backtracking (open count ≥ close count)

Free resources

Practice problems

Build it yourself

Compute the first 20 Catalan numbers three ways (recurrence DP, the binomial formula, and by counting the strings your 22 solution generates for n ≤ 8) and check they agree.

Inclusion–exclusion

To count things that have property A or B, adding |A| + |B| counts the overlap twice, so subtract it: |A ∪ B| = |A| + |B| − |A ∩ B|. With three sets you add the triple overlap back, and so on, alternating signs. Example: numbers from 1 to 100 divisible by 2 or 3 = 50 + 33 − 16 = 67. It's also how you count with upper limits in stars and bars: count without limits, subtract the cases where someone gets too many.

What to learn

  • Two-set and three-set inclusion–exclusion
  • Counting multiples of a or b with lcm
  • Stars and bars with an upper limit per group
  • Combining inclusion–exclusion with binary search ("the n-th number such that…")

Free resources

Practice problems

Build it yourself

Count the integers from 1 to 1,000,000 divisible by 2, 3 or 5 with inclusion–exclusion, then verify with a loop.

Derangements, Stirling numbers and probability

A few more families appear in harder problems. A derangement is a permutation where nobody stays in place (n people grab coats at random and nobody gets their own): Dₙ = (n − 1)(Dₙ₋₁ + Dₙ₋₂), and Dₙ / n! gets close to 1/e ≈ 0.368. Stirling numbers count permutations with k cycles (first kind) or ways to split n items into k non-empty groups (second kind). And probability with equally likely outcomes is just favourable count ÷ total count, so everything in this roadmap is also a probability tool. The pigeonhole principle (n + 1 pigeons in n holes means two share) proves that some things must happen without counting them.

What to learn

  • Derangements: the recurrence and the 1/e limit
  • Stirling numbers of the first and second kind, by DP
  • Probability as favourable ÷ total outcomes
  • The pigeonhole principle

Free resources

Practice problems

Build it yourself

Shuffle a list of 10 names a million times and measure how often nobody ends up in their original position. Compare with D₁₀ / 10! (about 0.3679).

Putting it together: a counting checklist

Faced with "count the ways…", work down this list: (1) Can I list them? If n is small (≤ 10 for permutations, ≤ 20 for subsets), backtracking or bitmasks are fine and easy to get right. (2) Order? Repetition? Pick nᵏ, P(n, k), C(n, k) or stars and bars. (3) Is it a product of independent parts? Count each part and multiply. (4) Is the complement easier? (5) Overlaps? Inclusion–exclusion. (6) No formula fits? Write a DP over "how many ways to build the first i items". Always check a formula against brute force on small inputs before trusting it.

What to learn

  • Deciding between "list them" and "count them" from the constraints
  • Breaking a problem into independent parts that multiply
  • Writing a counting DP when no formula fits
  • Checking a formula against brute force on small cases

Free resources

Practice problems

Build it yourself

Pick 5 problems from earlier stages that you solved with a formula and write a brute-force checker for each that compares the formula with exhaustive search for all small inputs.

Tools on this site

Am I ready? Stage 4 quiz

Why can't you compute fact[n] / fact[k] directly when working modulo 10⁹ + 7?

  1. Factorials are always even
  2. The modulus is too small
  3. Division doesn't work under a modulus; you multiply by the modular inverse instead
  4. You can, it's fine

(a mod p) / (b mod p) isn't (a / b) mod p in general. Multiply by b^(p − 2) mod p (Fermat) instead.

How many right/down paths cross a 4 × 4 grid of cells from corner to corner?

  1. C(6, 3) = 20
  2. 4! = 24
  3. 2⁶ = 64
  4. 16

3 downs and 3 rights in some order: choose which 3 of the 6 moves are downs, C(6, 3) = 20.

How many valid strings of 3 pairs of parentheses are there?

  1. 3
  2. 6
  3. 8
  4. 5

The third Catalan number: C(6, 3) / 4 = 5: ((())), (()()), (())(), ()(()), ()()().

How many numbers from 1 to 30 are divisible by 2 or 5?

  1. 21
  2. 18
  3. 15
  4. 12

15 + 6 − 3 (divisible by 10) = 18, by inclusion–exclusion.

A problem with n ≤ 10⁵ asks for a count modulo 10⁹ + 7. What's the right approach?

  1. Generate every arrangement with backtracking
  2. Use floating-point factorials
  3. Find a formula or DP, with precomputed factorials and inverses mod p
  4. Use bitmasks over all subsets

Listing is exponential. Large n plus a modulus means a counting formula or DP computed with modular arithmetic.

How to use this roadmap

  • Watch the animations first. Play Animation 1 with 4 items and 2 picks, then with 4 and 3, and see why the combination count is the permutation count divided by k!. Use Animation 2 whenever you're unsure which formula a question needs.
  • Work every example by hand. Counting is easy to get wrong by one factor. List the small cases on paper before you trust a formula.
  • Check formulas with code. For every formula you learn, write a brute force that lists all cases for small n and compare. This habit catches almost every mistake.
  • Tick problems as you solve them. Each list goes from easy to hard. Ticking the "What to learn" items tracks the topic itself: ticking the first marks it as in progress, ticking them all marks it as done. Use Export or Share progress to keep your progress.
  • Optional topics (dashed borders) don't count towards the percentage.

What's the difference between a permutation and a combination?

A permutation is an arrangement where order matters: choosing a president and a vice-president, a password, the top 3 in a race. A combination is a selection where order doesn't matter: a team, a lottery ticket, the toppings on a pizza. For the same n and k there are always more permutations than combinations, exactly k! times more, because every group of k items can be arranged in k! different orders. If repetition is allowed, ordered picks become nᵏ and unordered picks become C(n + k − 1, k).

Where does this show up in programming?

Coding interviews ask you both to generate them (subsets, permutations, combinations with backtracking) and to count them (formulas modulo 10⁹ + 7, grid paths, Catalan numbers). Counting also tells you whether brute force is feasible: 10! is 3.6 million, fine; 20! is 2.4 × 10¹⁸, not. For the wider set of algorithms, continue with the DSA roadmap, especially its backtracking and math topics.