AlgoViz

Combinations vs permutations

easy 15 min

Permutations count arrangements where order matters (AB is not BA); combinations count selections where it does not ({A, B} is {B, A}).

Video lesson · Chapter 1 of 6

Who is on the microphone?

0:00 / 5:34

Combinations vs. permutations

1:25Reel

Read caption

Moss casts two of four frogs, comparing six unordered duets with twelve assignments to distinct roles. Swap the singers. Does the outcome change?

How it works

Step through the idea, or press Play.

Step 1 of 3

Ask: does order matter?. If swapping two chosen items gives a different outcome, it is a permutation; if not, a combination

Understand it

Start here

Order matters, or it does not

Both ideas answer "in how many ways can I pick rr things from nn?". The only difference is whether the order of the picks counts. A permutation is an arrangement: ABC and CBA are different. A combination is a selection: {A,B,C}\{A, B, C\} and {C,B,A}\{C, B, A\} are the same group.

Permutation, written P(n, r) or nPr

  • Order matters: AB ≠ BA.
  • Passwords, PINs, rankings, podium places, seating plans.
  • "Pick and place in order."

Combination, written C(n, r), nCr or (nr)\binom{n}{r}

  • Order does not matter: {A,B}={B,A}\{A, B\} = \{B, A\}.
  • Teams, committees, lottery tickets, pizza toppings.
  • "Just pick, do not arrange."
  • Password: 123

    123, 321 and 213 open different locks. Wrong order means wrong password, so it is a permutation.

  • Committee of 3

    Alice, Bob and Cara form one committee whatever order you name them in, so it is a combination.

The decision

Which formula do I use?

Order matters? Repeats allowed?

The first question picks P or C. The second covers passwords (repeats allowed) and scoops of ice cream (repeats, no order).

Quick reference

ScenarioTypeCount
Arrange nn books on a shelfPermutation, r=nr = nn!n!
Podium: 1st, 2nd, 3rd of nn runnersPermutationn(n−1)(n−2)n(n-1)(n-2)
Pick 3 of 10 people, no rolesCombination(103)=120\binom{10}{3} = 120
All subsets of nn itemsSum of every (nr)\binom{n}{r}2n2^n
8-character password from 62 symbolsSequence with repeats628≈21862^8 \approx 218 trillion
The last row is why longer passwords are exponentially stronger.

Arrangements

Counting permutations

Fill rr positions one by one. The first position has nn choices, the second n−1n - 1 (one item is used up), and so on until the rr-th position has n−r+1n - r + 1. Multiply the choices together.

The permutation formula

P(n,r)=n!(n−r)!=n×(n−1)×⋯×(n−r+1)P(n, r) = \frac{n!}{(n-r)!} = n \times (n-1) \times \dots \times (n-r+1)
nn is the number of items and rr the number of positions. The (n−r)!(n-r)! cancels the tail of n!n! you never use. With r=nr = n, P(n,n)=n!P(n, n) = n! because 0!=10! = 1.

Arrange 2 of {A, B, C, D}

Multiply the choices per slot. That product is the formula.

Worked example

P(10,3)=10!7!=10×9×8=720P(10, 3) = \frac{10!}{7!} = 10 \times 9 \times 8 = 720
720 ways to give gold, silver and bronze to 3 of 10 runners.

Selections

Counting combinations

The combination formula

(nr)=n!r! (n−r)!=P(n,r)r!\binom{n}{r} = \frac{n!}{r!\,(n-r)!} = \frac{P(n, r)}{r!}
Read (nr)\binom{n}{r} as "nn choose rr". It is the permutation count divided by r!r!, the number of ways to order the rr chosen items.

Worked example

(103)=10!3! 7!=10×9×83×2×1=7206=120\binom{10}{3} = \frac{10!}{3!\,7!} = \frac{10 \times 9 \times 8}{3 \times 2 \times 1} = \frac{720}{6} = 120
120 ways to pick a 3-person team from 10 people. Six times fewer than the podium, because each team can stand on the podium in 3!=63! = 6 orders.
Python
from math import comb, perm, factorialprint(perm(10, 3), comb(10, 3))   # 720 120print(perm(4, 2), comb(4, 2))     # 12 6print(factorial(10) // factorial(7))                    # 720, by handprint(factorial(10) // (factorial(3) * factorial(7)))   # 120, by hand
Python 3.8+ has both counts built in, exact for any size.
Edit and run it in your browser

The key insight

Why we divide by r!

Pick 2 from {A, B, C}

Permutations, P(3,2)=6P(3, 2) = 6Same group asCombinations, (32)=3\binom{3}{2} = 3
AB, BA{A,B}\{A, B\}1
AC, CA{A,C}\{A, C\}1
BC, CB{B,C}\{B, C\}1
Every group of 2 shows up 2!=22! = 2 times among the permutations.

Six arrangements collapse into three groups

Collapsing each group's r!r! orderings into one is exactly a division by r!r!.

Permutations = combinations × orderings

P(n,r)=(nr)×r!6=3×2P(n, r) = \binom{n}{r} \times r! \qquad 6 = 3 \times 2
Every arrangement is "first choose the group, then order it". So the arrangement count is the group count times r!r!.

Without factorials

Pascal's triangle

Write (nr)\binom{n}{r} in rows: row nn holds (n0)\binom{n}{0} to (nn)\binom{n}{n}. Each row starts and ends with 1, and every inner number is the sum of the two numbers above it. You can compute any (nr)\binom{n}{r} with additions only, and the intermediate numbers never get bigger than the answer.

Pascal's rule

(nr)=(n−1r−1)+(n−1r)\binom{n}{r} = \binom{n-1}{r-1} + \binom{n-1}{r}
Look at one item, say the last. Either it is in the group (choose r−1r-1 more from the other n−1n-1) or it is not (choose all rr from the other n−1n-1). Example: (42)=(31)+(32)=3+3=6\binom{4}{2} = \binom{3}{1} + \binom{3}{2} = 3 + 3 = 6.
Row nnValues (n0)…(nn)\binom{n}{0} \dots \binom{n}{n}Row sum
011 = 202^0
11 12 = 212^1
21 2 14 = 222^2
31 3 3 18 = 232^3
41 4 6 4 116 = 242^4
51 5 10 10 5 132 = 252^5
61 6 15 20 15 6 164 = 262^6
Read (nr)\binom{n}{r} at row nn, position rr, both counted from 0: (62)=15\binom{6}{2} = 15.

Every row sums to a power of two

(n0)+(n1)+⋯+(nn)=2n\binom{n}{0} + \binom{n}{1} + \dots + \binom{n}{n} = 2^n
Choosing 0, 1, … or nn items covers every subset, and nn items have 2n2^n subsets. That is why the subsets problem always has 2n2^n answers.

Shortcuts

Identities worth knowing

IdentityFormulaWhy
Edges(n0)=(nn)=1\binom{n}{0} = \binom{n}{n} = 1One way to choose nothing, one way to choose everything
Symmetry(nr)=(nn−r)\binom{n}{r} = \binom{n}{n-r}Choosing who is in is the same as choosing who is out
Pairs(n2)=n(n−1)2\binom{n}{2} = \frac{n(n-1)}{2}Handshakes among nn people; pairs in a nested loop
All ordersP(n,n)=n!P(n, n) = n!Arrange every item
Repeated itemsn!k1! k2!⋯\frac{n!}{k_1!\,k_2!\cdots}Arrangements of a word with repeated letters
Python
def n_choose_r(n, r):    if r < 0 or r > n:        return 0    r = min(r, n - r)            # symmetry: fewer steps    result = 1    for k in range(1, r + 1):        result = result * (n - r + k) // k   # always an exact integer    return resultprint(n_choose_r(4, 2))     # 6print(n_choose_r(10, 3))    # 120print(n_choose_r(100, 98))  # 4950, computed as C(100, 2)
Compute C(n, r) exactly without building huge factorials: multiply and divide one step at a time.
Edit and run it in your browser

In code

Generating them with backtracking

One backtracking call

The skeleton is the same. Only the rule for which items are candidates changes.
Python
def permute(nums):    result, path = [], []    used = [False] * len(nums)    def backtrack():        if len(path) == len(nums):            result.append(path[:])            return        for i in range(len(nums)):            if used[i]:                continue            used[i] = True            path.append(nums[i])            backtrack()            path.pop()            used[i] = False    backtrack()    return resultdef combine(n, k):    result, path = [], []    def backtrack(start):        if len(path) == k:            result.append(path[:])            return        for i in range(start, n + 1):            path.append(i)            backtrack(i + 1)     # the key line            path.pop()    backtrack(1)    return resultprint(permute([1, 2, 3]))   # 6 orderingsprint(combine(4, 2))        # [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
The two patterns to memorise. Run it and compare the outputs.
Edit and run it in your browser

Permutations: used[] array

  • Loop over every index each time.
  • Skip indexes already in the path.
  • Undo both path.pop() and used[i] = False.

Combinations: start index

  • Loop from start only.
  • Recurse with i + 1 so the next pick comes strictly later.
  • No used[] needed: earlier items are never offered again.

Edge case

When the input has duplicates

With repeated values, plain backtracking prints the same arrangement more than once: the two 1s in [1, 1, 2] are interchangeable. The count of distinct arrangements divides out the orderings of each repeated value.

Arrangements of a multiset

n!k1! k2!⋯km!e.g. aab:3!2! 1!=3\frac{n!}{k_1!\,k_2!\cdots k_m!} \qquad \text{e.g. } \texttt{aab}: \frac{3!}{2!\,1!} = 3
kik_i is how many times value ii repeats. aabb has 4!2! 2!=6\frac{4!}{2!\,2!} = 6 distinct arrangements, not 24.
Python
def permute_unique(nums):    nums = sorted(nums)    result, path = [], []    used = [False] * len(nums)    def backtrack():        if len(path) == len(nums):            result.append(path[:])            return        for i in range(len(nums)):            if used[i]:                continue            if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:                continue         # same value, same position: already tried            used[i] = True            path.append(nums[i])            backtrack()            path.pop()            used[i] = False    backtrack()    return resultprint(permute_unique([1, 1, 2]))   # [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
Sort, then skip a value equal to the previous one when that previous copy is not in use.
Edit and run it in your browser

Cost

How expensive is generating them?

TaskResultsTimeExtra space
All permutations of nnn!n!O(n!⋅n)O(n! \cdot n)O(n)O(n) recursion
Permutations of rr from nnP(n,r)P(n, r)O(P(n,r)⋅r)O(P(n, r) \cdot r)O(r)O(r)
Combinations of rr from nn(nr)\binom{n}{r}O((nr)⋅r)O(\binom{n}{r} \cdot r)O(r)O(r)
All subsets of nn2n2^nO(2n⋅n)O(2^n \cdot n)O(n)O(n) recursion
The extra factor is the cost of copying each result. Space excludes the output itself.

Factorial beats exponential

10!=3,628,800210=1,02420!≈2.4×101810! = 3{,}628{,}800 \qquad 2^{10} = 1{,}024 \qquad 20! \approx 2.4 \times 10^{18}
Each extra item multiplies n!n! by nn but only doubles 2n2^n.

Why engineers care

Where the counts show up

  • Complexity analysis

    Brute force over orderings is O(n!)O(n!), over subsets O(2n)O(2^n). Knowing the count tells you when to reach for DP.

  • Query optimisers

    Joining nn tables can happen in n!n! orders: 120 for 5 tables, 3,628,800 for 10. Optimisers must prune.

  • Security

    A password of length nn over kk symbols has knk^n options. 8 characters from 62 gives about 218 trillion.

  • Feature selection

    Choosing 10 of 100 features: (10010)≈17\binom{100}{10} \approx 17 trillion subsets, so exhaustive search is out.

  • Interview staples

    Permutations, Permutations II, Combinations, Subsets, Combination Sum and Next Permutation all build on this page.

  • Probability

    Odds are favourable outcomes over total outcomes, and both are usually a (nr)\binom{n}{r} or a P(n,r)P(n, r).

Recap

Key takeaways

Key points

  • Ask "does order matter?" first: yes is a permutation, no is a combination.
  • P(n,r)=n!(n−r)!P(n, r) = \frac{n!}{(n-r)!}: multiply the choices for each position, n×(n−1)×…n \times (n-1) \times \dots
  • (nr)=n!r! (n−r)!=P(n,r)r!\binom{n}{r} = \frac{n!}{r!\,(n-r)!} = \frac{P(n, r)}{r!}: divide out the r!r! orderings of each group.
  • Pascal's rule (nr)=(n−1r−1)+(n−1r)\binom{n}{r} = \binom{n-1}{r-1} + \binom{n-1}{r} builds every value with additions; each row sums to 2n2^n.
  • Backtracking: permutations use a used[] array, combinations recurse with i + 1.
  • Repeats allowed change the formula (nrn^r), and duplicate inputs need sort-and-skip.
  • Listing all permutations is O(n!⋅n)O(n! \cdot n); count with a formula whenever you only need the number.

Sources