O(n!) — factorial complexity

O(n!) — factorial complexity

This is the peak of computational nightmares. Factorial complexity means the number of operations grows as the product of all integers up to n. For n = 10, that's already 3,628,800 variants. And yes, all of them have to be processed.

10! = 10 × 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1 = 3 628 800

Example: generating all possible permutations of elements

function permutations(array $items): array {
    if (count($items) <= 1) return [$items];

    $result = [];
    foreach ($items as $key => $item) {
        $remaining = $items;
        unset($remaining[$key]);
        foreach (permutations(array_values($remaining)) as $perm) {
            $result[] = array_merge([$item], $perm);
        }
    }
    return $result;
}

This code generates all possible permutations of the array's elements. And if there are 8 of them, that's already 40,320 variants. It may look innocent — until production goes down on Black Friday.

Factorial complexity is always a last resort. If a task involves trying every option, first look for an approximation, a greedy algorithm or a heuristic.

That's the end of the series.

← Previous: O(2ⁿ) — exponential complexity · Whole series


First published in Ukrainian in the Telegram channel “Created to die” on June 27, 2025.