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}).

See it run

Build every ordered pick of 2 from {A, B, C, D}, fold the 12 into 6 unordered picks, grow Pascal's triangle row by row, and watch n! leave 2^n behind.

Operations

Permutation Generator

Order matters: AB and BA are different. Fill $r$ positions one at a time from $n$ items, never reusing an item, so $P(n, r) = n \times (n-1) \times \dots \times (n-r+1) = \frac{n!}{(n-r)!}$.

Step 1 of 8

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

  1. A
  2. B
  3. C
  4. D

slots

  1. ?
  2. ?
n = 4r = 2P(4,2) = ?

We want every way to fill 2 ordered positions from 4 items. Order matters, so AB (A first, B second) and BA are two different permutations. Think gold and silver medals for 4 runners.

Step 1: Arrange 2 of {A, B, C, D}

from math import factorialdef n_p_r(n, r):    return factorial(n) // factorial(n - r)   # n x (n-1) x ... x (n-r+1)def permutations(items, r):    result, path = [], []    used = [False] * len(items)    def backtrack():        if len(path) == r:            result.append("".join(path))            return        for i in range(len(items)):            if used[i]:                continue            used[i] = True            path.append(items[i])            backtrack()            path.pop()            used[i] = False    backtrack()    return resultprint(n_p_r(4, 2))               # 12print(permutations("ABCD", 2))   # ['AB', 'AC', 'AD', 'BA', 'BC', ...]
Time
O(P(n, r) · r)
Space
O(r) besides the output
P(4, 2)
4 × 3 = 12
all of n (r = n)
n! arrangements

Permutation backtracking: loop over every index, skip the used ones, and undo both the path and the used flag after the recursive call.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Using nCr when order matters (or nPr when it does not)

    critical

    Ask one question first: does swapping two chosen items give a different outcome? Podium places, PINs and seatings: yes, permutation. Teams, lottery tickets and pizza toppings: no, combination.

    Wrong
    # gold, silver, bronze among 10 runnersways = comb(10, 3)   # 120, too few
    Right
    ways = perm(10, 3)   # 720 = 10 x 9 x 8# a 3-person team from 10: comb(10, 3) = 120
  • Recursing with start + 1 instead of i + 1

    critical

    The next pick must come after the item just chosen, which is index i, not after the loop's starting point. Using start + 1 lets earlier items come back and produces duplicates like BA.

    Wrong
    for i in range(start, len(items)):    path.append(items[i])    backtrack(start + 1)   # duplicates    path.pop()
    Right
    for i in range(start, len(items)):    path.append(items[i])    backtrack(i + 1)       # strictly after items[i]    path.pop()
  • Forgetting to undo the used flag

    major

    Backtracking must restore the state it changed. If usedi stays True after the call returns, item i is never offered again in other branches and most permutations go missing.

    Wrong
    used[i] = Truepath.append(nums[i])backtrack()path.pop()             # used[i] is still True
    Right
    used[i] = Truepath.append(nums[i])backtrack()path.pop()used[i] = False
  • Appending the path itself instead of a copy

    major

    path is one list that keeps changing. Appending it stores the same object many times, and after backtracking every stored entry is empty.

    Wrong
    if len(path) == r:    result.append(path)      # all entries end up []
    Right
    if len(path) == r:    result.append(path[:])   # snapshot of this moment
  • Dividing factorials with / instead of //

    minor

    True division returns a float, which loses exactness past about 2^53 and can print 1.2e+29 instead of an exact integer. Use integer division, or math.comb and math.perm.

    Wrong
    ways = factorial(30) / (factorial(15) * factorial(15))
    Right
    ways = factorial(30) // (factorial(15) * factorial(15))ways = comb(30, 15)   # 155117520, exact
  • Not skipping duplicates in the input

    major

    With repeated values such as [1, 1, 2], plain backtracking outputs the same arrangement more than once. Sort first, then skip a value equal to the previous one when the previous copy is not in use.

    Wrong
    for i in range(len(nums)):    if used[i]:        continue    ...                      # [1, 1, 2] printed twice
    Right
    nums.sort()for i in range(len(nums)):    if used[i] or (i > 0 and nums[i] == nums[i - 1] and not used[i - 1]):        continue    ...

Interview tips

  • Spot it fast

    • "How many ways" plus ranks, positions or sequences: permutation.
    • "How many ways" plus teams, groups or subsets: combination.
    • "List all" arrangements or selections: backtracking.
    • Many C(n, r) values, or choose-or-skip DP: Pascal's rule.
  • Numbers to know cold

    • P(4, 2) = 12 and C(4, 2) = 6.
    • 10P3 = 720 and 10C3 = 120.
    • Row 4 of Pascal: 1 4 6 4 1, sum 16 = 2^4.
    • 10! = 3,628,800; 2^10 = 1,024.
  • Say it in the interview

    • "Order matters here, so I count with n! / (n - r)!."
    • "Each group has r! orderings, so I divide the permutation count by r!."
    • "Generating all permutations is O(n! · n) because of the copy at each leaf."
  • Traps

    • Repetition allowed changes the formula: n^r ordered, C(n + r - 1, r) unordered.
    • Duplicates in the input need sort-and-skip.
    • Copy the path when you record a result.