AlgoViz

O(n!) factorial time

easy 15 min

O(n!) means the work grows like n × (n - 1) × ...

See it run

Watch the permutation tree branch 3, 2, 1 ways, a swap backtracker list all 6 orders, brute force try every route through 4 cities, and n! leave 2ⁿ behind.

Operations

Permutation tree

Build every ordering of [1, 2, 3] as a tree: 3 choices for the first slot, 2 for the second, 1 for the last.

Step 1 of 7

Start with an empty arrangement

[ ]

remaining = [1, 2, 3]

The root is the empty order [ ] with 3 numbers still to place. Every path from the root to a leaf will be one permutation.

Step 1: Start with an empty arrangement

def permutations(nums):    result = []    def build(path, remaining):        if not remaining:            result.append(path)            return        for i in range(len(remaining)):            build(path + [remaining[i]],                  remaining[:i] + remaining[i + 1:])    build([], nums)    return result
Time
O(n · n!)
Space
O(n)
n = 3
6 leaves
n = 10
3,628,800 leaves

Count a permutation tree level by level: n branches, then n - 1, then n - 2. The product of the branching factors is the number of leaves, n!.

Common mistakes

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

  • Appending the working list instead of a copy

    critical

    The backtracker reuses one list. Appending it stores the same object six times, and after the final undo every entry reads [1, 2, 3].

    Wrong
    if start == len(arr):    result.append(arr)       # same list every time
    Right
    if start == len(arr):    result.append(arr[:])    # snapshot this order
  • Forgetting to undo the swap

    critical

    Without the second swap the array stays scrambled when the loop moves on, so later branches start from the wrong state and produce repeats while missing other orders.

    Wrong
    for i in range(start, len(arr)):    arr[start], arr[i] = arr[i], arr[start]    backtrack(start + 1)     # no undo
    Right
    for i in range(start, len(arr)):    arr[start], arr[i] = arr[i], arr[start]    backtrack(start + 1)    arr[start], arr[i] = arr[i], arr[start]   # undo
  • Brute-forcing orders for large n

    major

    15! is about 1.3 trillion and 20! about 2.4 × 10¹⁸. Factorial brute force only works up to about 10 to 12 items; beyond that use a DP or a heuristic.

    Wrong
    best = min(tour_length(p) for p in permutations(range(20)))# 2.4 * 10**18 orders: never finishes
    Right
    best = held_karp(dist)    # O(n^2 * 2^n): about 4 * 10**8 steps at n = 20
  • Duplicates produce repeated orders

    major

    Swapping equal values creates the same arrangement twice. [1, 1, 2] has only 3 distinct orders, but the plain algorithm returns 6.

    Wrong
    permute([1, 1, 2])        # 6 results, 3 repeated
    Right
    nums.sort()# in the loop: skip i if used[i], or if# nums[i] == nums[i - 1] and not used[i - 1]
  • Counting n! routes for TSP

    minor

    Starting the loop at every city repeats each tour n times. Fix city 0 and permute the rest: (n - 1)! routes, or (n - 1)!/2 distinct tours for symmetric distances.

    Wrong
    for perm in permutations(range(n)):       # n! routes
    Right
    for perm in permutations(range(1, n)):    # (n - 1)! routes    route = (0,) + perm + (0,)
  • Materialising every permutation in memory

    minor

    list(permutations(items)) stores n · n! values at once. If you only need to scan them, iterate the generator so memory stays O(n).

    Wrong
    perms = list(permutations(items))   # O(n * n!) memorybest = min(perms, key=score)
    Right
    best = min(permutations(items), key=score)   # one order at a time

Interview tips

  • How to explain it

    • O(n!) means trying every ordering: n choices for the first slot, n - 1 for the second, down to 1.
    • n! = n · (n - 1)!, so each extra item multiplies the work by n, not by a constant.
    • Returning all permutations is O(n · n!) because each output has length n.
    • Brute-force TSP checks (n - 1)!/2 distinct tours: fix the start, halve for direction.
  • Spot it in code

    • `for i in range(start, n)` with swap, recurse on `start + 1`, swap back.
    • Recursing on `remaining` minus one item inside a loop over `remaining`.
    • `itertools.permutations` over the whole input.
    • A loop of n around a call on n - 1: T(n) = n · T(n - 1).
  • Memory tricks

    • Seat assignment: n chairs for the first guest, then n - 1, down to 1.
    • 5! = 120, 10! ≈ 3.6 million, 20! ≈ 2.4 × 10¹⁸.
    • n! passes 2ⁿ at n = 4 and never looks back.
    • Subsets double (2ⁿ); permutations multiply (n!).
  • Watch out

    • Brute force over orders is practical only up to about n = 10 to 12.
    • Counting arrangements is cheap with a formula; only listing them is factorial.
    • Duplicates in the input need a skip rule or you return repeats.