Factorial-Time Sorting and Exact Permutation Enumeration

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

This two-part conceptual interview question requires verbal algorithmic reasoning rather than live coding:

  1. Slowest guaranteed-terminating sort: Propose the least efficient sorting method you can justify that still finishes on every n-element input (including arrays with duplicate values) and outputs a non-decreasing sequence. State what ground rules prevent trivial busy-work, derive worst-case and average-case runtime by counting candidate arrangements and per-candidate work, and contrast deterministic search against a random-shuffle alternative.
  2. Exact single-pass permutation generation: Describe an algorithm that enumerates every permutation of n elements once and only once without storing previously visited arrangements. Justify why zero arrangements are skipped or repeated, analyze its per-step, total, and auxiliary-memory complexity, explain how duplicate values behave, and show how to wire the generator into your sort with immediate early stopping once a sorted candidate is reached.

Scope & Expectations

  • Non-padding model & termination: Define rules that make "slowest valid sort" mathematically meaningful and prove deterministic termination versus probabilistic shuffling.
  • Factorial complexity breakdown: Combine the n! candidate count with per-candidate construction and is_sorted verification costs across best, average, and worst cases.
  • Exact permutation stepping: Walk through an in-place or recursive enumeration method, prove every arrangement appears once, and state per-call, amortized, total, and extra-space bounds.
  • Duplicates & integration: Explain multiset duplicate behavior and demonstrate why permuting index positions (0..n-1) cleanly drives the sort with early exit.

Step-by-step walkthrough

  1. Establish ground rules that rule out artificial stalling

    Taken literally, "what is the slowest correct sorting algorithm?" has no answer. You could take merge sort, put a useless loop in front that counts to 2^(2^n), and get a slower correct sort; someone else could count to 2^(2^(2^n)) and beat you again.

    To make "worst" well-defined, state a rule that forbids artificial padding and forces every step to do genuine search work: - The only way the algorithm may inspect the input values is by calling a black-box check is_sorted(candidate) on a full arrangement of the array. - Every check must have a chance of succeeding — the algorithm may never test the same arrangement twice.

    Under that rule, each failed check tells you only "this one arrangement is not sorted," teaching you nothing about the remaining arrangements. In the worst case, an adversary can hide the sorted arrangement at the very end of your search order, forcing n! checks.

    Settle the three clarifying questions up front as well: - Termination: The main deterministic answer must always terminate with a sorted array. - Running-time cases: Give both worst-case and average-case bounds for the deterministic sort, and contrast them with expected vs. worst-case bounds for the randomized variant. - Repeated values: Allowed — we will show both index-based counting (n!) and distinct-multiset counting (n! / (c1! · c2! · ...)).

  2. Part 1a: Permutation sort — generate, test, and count the work

    Permutation sort turns that black-box rule directly into an algorithm: 1. Enumerate the arrangements (permutations) of the n input items one at a time without repeats. 2. Check each candidate with is_sorted (at most n - 1 adjacent comparisons). 3. Return the first candidate that passes.

    def is_sorted(seq):
        for i in range(len(seq) - 1):
            if seq[i] > seq[i + 1]:
                return False
        return True
    

    Why it always terminates with a correct answer: Any finite collection of comparable values has at least one non-decreasing arrangement. There are finitely many (n!) index arrangements, and our generator visits every single one without repeating, so is_sorted is guaranteed to return True within at most n! checks.

    Running-time derivation: - How many candidates: Slot 0 has n choices, slot 1 has n - 1 remaining choices, down to 1 choice for slot n - 1, giving n * (n - 1) * ... * 1 = n! index permutations. - Cost per candidate: Building a candidate list of length n takes Θ(n) time, and is_sorted takes O(n) time (n - 1 comparisons when sorted, and on average fewer than 2 comparisons when unsorted because the first pair already fails half the time). - Total worst-case time — Θ(n · n!): Materializing and testing up to n! candidates costs Θ(n · n!) (or Θ(n!) if we step an index array in place in amortized O(1) time and check values[order[i]] <= values[order[i + 1]] without copying). - Average-case time — Θ(n · n!): On a random ordering of n distinct items, the sorted arrangement is equally likely to sit at any of the n! positions in our enumeration, averaging (n! + 1) / 2 candidates.

    Concrete numbers show how fast n! explodes:

    n =  5  ->                  120 candidates  (instant)
    n = 10  ->            3,628,800 candidates  (~0.04 s at 10^8 checks/s)
    n = 13  ->        6,227,020,800 candidates  (~1 minute at 10^8 checks/s)
    n = 20  ->  ~2.43 × 10^18 candidates        (~77 years at 10^9 checks/s)
    
  3. Part 1b: Compare with the randomized variant (bogosort)

    What if, instead of enumerating systematically, we randomly shuffle the array before each check? That is bogosort (also called monkey sort or random-shuffle sort):

    import random
    
    
    def bogosort(values):
        candidate = list(values)
        while not is_sorted(candidate):
            random.shuffle(candidate)
        return candidate
    

    How bogosort's guarantees differ from permutation sort: - Expected running time — Θ(n · n!): For n distinct elements, each uniform Θ(n) shuffle lands on the unique sorted order with probability 1 / n!. Waiting for an event of probability p = 1 / n! takes 1 / p = n! shuffles on average, so expected work is Θ(n · n!) — the same asymptotic order as permutation sort (about twice as many tries as permutation sort's (n! + 1) / 2 average). - Worst-case running time — unbounded (∞): Because bogosort has no memory, it breaks our "never test the same arrangement twice" rule and can repeat unsorted shuffles indefinitely. After t shuffles, the probability of still being unsorted is (1 - 1 / n!)^t, which is strictly greater than 0 for every finite t. Bogosort terminates with probability 1, not with deterministic certainty.

  4. Part 2a: Enumerate every permutation in lexicographic order

    To generate every arrangement without keeping a Θ(n · n!) hash set of previously seen candidates, list them in lexicographic order — dictionary order, where two sequences are compared at the leftmost index where they differ ([1, 3, 2] comes before [2, 1, 3] because 1 < 2 at index 0). For [1, 2, 3], the 3! = 6 arrangements in dictionary order are:

    [1, 2, 3] -> [1, 3, 2] -> [2, 1, 3] -> [2, 3, 1] -> [3, 1, 2] -> [3, 2, 1]
    

    Given any current arrangement a, next_permutation(a) steps in place to the immediate next dictionary arrangement in four small moves (traced on [1, 4, 3, 2] -> [2, 1, 3, 4]):

    Start:   [1,  4,  3,  2]
              ^   ---------
            i = 0  descending suffix (already as large as possible on its own!)
    
    1. Find rightmost pivot i with a[i] < a[i + 1]:
         4 >= 3, 3 >= 2, 1 < 4  ->  pivot is i = 0 (value 1).
    
    2. Find rightmost j > i in the suffix with a[j] > a[i]:
         smallest value in [4, 3, 2] larger than 1 is at j = 3 (value 2).
    
    3. Swap a[i] and a[j]:
         [2,  4,  3,  1]   (notice suffix [4, 3, 1] is STILL descending!)
    
    4. Reverse suffix a[i + 1 .. n - 1] so it becomes smallest (ascending):
         [2,  1,  3,  4]   <- immediate next dictionary permutation!
    
    def next_permutation(a):
        """Advance list a in place to its next lexicographic arrangement and return True.
        If a is already the last (non-increasing) arrangement, reverse it to ascending and return False."""
        # 1. Find rightmost pivot index i where a[i] < a[i + 1]
        i = len(a) - 2
        while i >= 0 and a[i] >= a[i + 1]:
            i -= 1
    
        if i < 0:
            # Entire list is non-increasing: no larger arrangement exists
            a.reverse()
            return False
    
        # 2. Find rightmost suffix index j > i with a[j] > a[i]
        j = len(a) - 1
        while a[j] <= a[i]:
            j -= 1
    
        # 3. Swap pivot with the smallest suffix item larger than it
        a[i], a[j] = a[j], a[i]
    
        # 4. Reverse suffix a[i + 1..] from non-increasing to non-decreasing
        left = i + 1
        right = len(a) - 1
        while left < right:
            a[left], a[right] = a[right], a[left]
            left += 1
            right -= 1
        return True
    
  5. Part 2b: Why every permutation appears once, and what it costs

    Why every arrangement is produced once and only once: - Because every element after i satisfies a[k] >= a[k + 1], the suffix a[i + 1..] is already in descending order — no arrangement sharing the prefix a[0..i] can be dictionary-larger. - Therefore, the very next arrangement must increase index i by the smallest available amount (swapping in the rightmost a[j] > a[i]) and then make a[i + 1..] as small as possible (reversing the still-descending suffix into ascending order). - Because next_permutation jumps to the immediate successor with nothing skipped in between, and dictionary order is a strict total order on a finite set, starting at the smallest (ascending) arrangement and stepping until False visits every arrangement once, with zero duplicates and zero omissions.

    Time and space complexity: - Per call (worst case) — O(n): Scanning and reversing can span the whole array (e.g., [1, 4, 3, 2] -> [2, 1, 3, 4]). - Per call (amortized) — O(1): Amortized means averaged across the full run of n! steps. Long descending suffixes are rare: half of all permutations end with a[n - 2] < a[n - 1] (suffix length 1), only 1 / 2! have a descending suffix of length >= 2, 1 / 3! have length >= 3, and in general 1 / k! have length >= k. Summing 1/1! + 1/2! + 1/3! + ... bounds the average suffix length at e - 1 ≈ 1.72 elements! - Total time: Θ(n!) to step in place through all n! arrangements, or Θ(n · n!) if you copy or print a length-n list at every step. - Extra space — O(1): Everything happens in place via swaps on a.

  6. Part 2c: Repeated values and alternative generators

    What happens when the input has repeated values: - Notice the strict inequalities a[i] < a[i + 1] and a[j] > a[i] in next_permutation. Equal elements are never chosen as a pivot or swapped with each other, so every call produces a strictly larger value sequence in dictionary order. - If you start from the sorted array [1, 1, 2], next_permutation produces [1, 1, 2] -> [1, 2, 1] -> [2, 1, 1] and then returns False — visiting each distinct arrangement once (3! / 2! = 3 instead of 6). In general, if values have multiplicities c1, c2, ..., starting from ascending order produces all n! / (c1! · c2! · ...) distinct arrangements with zero duplicates. (Caution: you must start from ascending order; starting from [2, 1, 1] stops immediately because [2, 1, 1] is already the last dictionary sequence!)

    Alternative permutation generators to know: - Recursive backtracking: Builds a current prefix slot by slot using a boolean used[0..n-1] array (O(n) recursion depth and O(n) extra space, Θ(n · n!) total time). To avoid duplicates on repeated values, sort first and skip k when a[k] == a[k - 1] and not used[k - 1]. - Heap's algorithm: Steps through all n! arrangements so that each consecutive arrangement differs by just one swap (O(n!) total swaps, O(n) state array, non-lexicographic order).

  7. Part 2d: Plug the generator into permutation sort and stop early

    There is a crucial trap when connecting next_permutation to permutation_sort: permute the index array order = [0, 1, ..., n - 1], not values itself! Why? 1. Running next_permutation directly on values compares values[i] with values[i + 1], violating our black-box is_sorted-only rule — in fact, stepping values until next_permutation returns False reverses values into sorted order without ever calling is_sorted! 2. Worse, starting next_permutation on an arbitrary values like [3, 2, 1] stops after 1 step without ever visiting [1, 2, 3] unless you sort values first (which begs the question!).

    Permuting order = [0, 1, ..., n - 1] solves both problems cleanly: 0, 1, ..., n - 1 already starts in ascending order without inspecting values, visits all n! rearrangements of values, and stops the instant is_sorted(candidate) succeeds:

    def permutation_sort(values):
        # Start with identity index order [0, 1, ..., n - 1], which is already ascending
        order = list(range(len(values)))
        while True:
            candidate = [values[idx] for idx in order]
            if is_sorted(candidate):
                # Guaranteed to succeed on or before the n!-th arrangement
                return candidate
            next_permutation(order)
    

    Trace permutation_sort([3, 1, 2]):

    Step   order        candidate = [values[k] for k in order]   is_sorted?
      1    [0, 1, 2]    [3, 1, 2]                                False (3 > 1)
      2    [0, 2, 1]    [3, 2, 1]                                False (3 > 2)
      3    [1, 0, 2]    [1, 3, 2]                                False (3 > 2)
      4    [1, 2, 0]    [1, 2, 3]                                True  -> return [1, 2, 3]!
    
    • Early stopping (best case) — O(n): On an already sorted input [1, 2, 3], step 1 (order = [0, 1, 2]) passes is_sorted immediately.
    • Worst case — Θ(n · n!): On a reversed input of distinct values [3, 2, 1], the sorted order requires order = [2, 1, 0] — the very last of the n! index orders — checking every candidate.
    • Extra space — O(n): Only order and the current candidate list are held in memory at any moment.

Intuition & how it works

Imagine opening a combination padlock whose shackle gives zero feedback until the full code is dialed in and pulled. Bogosort spins the dials at random before every pull — it usually opens after n! tries on average, yet nothing stops it from repeating bad combinations forever. Permutation sort turns the dials like an odometer in strict lexicographic order (dictionary order: 012, 021, 102, ...), guaranteeing that every arrangement of the n items is tested at most once and the sorted order is always reached.

Without a ground rule forbidding pointless busy-work (like counting to 2^(2^n) before running merge sort), there is no "slowest" sorting algorithm because any algorithm can be padded endlessly. Once we require that every step test a fresh candidate via is_sorted with no repeats, the naive way to enumerate candidates — keeping a hash set of all previously tested lists — wastes Θ(n · n!) memory. Stepping an index array forward in dictionary order (next_permutation) visits every arrangement once using just O(1) extra space beyond the array itself.

Walk through values = [3, 1, 2] (n = 3, so 3! = 6 index permutations): - Start with index positions order = [0, 1, 2], giving candidate [3, 1, 2] (3 > 1, unsorted). - Advance order in dictionary order to [0, 2, 1] -> [3, 2, 1] (unsorted), then [1, 0, 2] -> [1, 3, 2] (unsorted). - Next, next_permutation([1, 0, 2]) finds rightmost ascent 0 < 2 at index 1, swaps 0 and 2, and gets [1, 2, 0] -> candidate [1, 2, 3], which passes is_sorted and stops early on try 4 of 6!

Key points

  • "Worst" requires a non-padding rule: Restricting inspection to is_sorted(candidate) on full arrangements and banning duplicate tests caps the worst case at n! checks, making permutation sort optimal-worst under that model.
  • Permutation sort guarantees termination in Θ(n · n!) worst-case time: Every comparable array has at least one sorted ordering among the n! index permutations; building a length-n candidate and running is_sorted costs Θ(n) per try (O(n) best case when already sorted; Θ(n · n!) worst case when reversed).
  • Bogosort trades worst-case termination for statelessness: Uniformly shuffling until sorted takes n! shuffles on average (Θ(n · n!) expected time on distinct keys), but has no finite worst-case bound because random shuffles can repeat failed arrangements indefinitely.
  • next_permutation steps in O(1) amortized time and O(1) extra space: Finding the rightmost ascent a[i] < a[i + 1], swapping a[i] with the rightmost a[j] > a[i], and reversing a[i + 1..] produces the immediate dictionary successor; amortized (averaged across all n! steps) suffix length is 1/1! + 1/2! + ... ≈ e - 1 ≈ 1.72.
  • Repeated values collapse cleanly under strict < and >: Starting from sorted values with multiplicities c1, c2, ..., next_permutation emits each of the n! / (c1! · c2! · ...) distinct value arrangements once, whereas itertools.permutations and plain backtracking emit duplicate value tuples unless filtered.
  • Permute indices, not values, inside permutation sort: Running next_permutation on order = [0, 1, ..., n - 1] starts in ascending order automatically without comparing input values outside is_sorted.

Common mistakes

  • Saying "bogosort is O(n!)" without naming the case or per-step cost: Bogosort's expected time on distinct elements is Θ(n · n!) (each shuffle costs Θ(n)), and its worst-case time is unbounded (∞), not O(n!).
  • Claiming bogosort is guaranteed to terminate: Terminating with probability 1 is weaker than deterministic termination — the failure sequence (1 - 1 / n!)^t stays positive for every finite t.
  • Forgetting the Θ(n) copy cost per permutation: Materializing a new tuple or list of length n on each of n! steps gives Θ(n · n!) total work; Θ(n!) holds only when stepping in place and checking values[order[i]] <= values[order[i + 1]] with early exit.
  • Storing a seen set of permutations in memory: Saving previously generated permutations requires Θ(n · n!) RAM (> 36 million ints already at n = 10), whereas next_permutation needs O(1) extra space.
  • Starting value-based next_permutation on an unsorted array: Calling next_permutation directly on [3, 1, 2] visits only arrangements dictionary-larger than [3, 1, 2] ([3, 2, 1]) and completely misses [1, 2, 3]!

Follow-up questions

  • Suppose you shuffle the elements uniformly at random before each sortedness check: what is the expected runtime, and must the loop eventually halt? With n distinct elements, each Θ(n) uniform shuffle hits the unique sorted order with probability 1 / n!. That trial count follows a geometric distribution (number of independent coin flips of success probability p until the first heads, with mean 1 / p), giving n! expected shuffles and Θ(n · n!) expected time (faster when duplicate values exist, since c1! · c2! · ... arrangements are sorted). It is not guaranteed to terminate: mathematically (1 - 1 / n!)^t > 0 for every t, and in practice a pseudo-random number generator (PRNG) — a deterministic state machine mimicking randomness — has finitely many internal states (Python's Mersenne Twister has 2^19937 - 1 states, which is smaller than n! once n >= 2081, so most permutations of 2081 items can never even be produced by random.shuffle!).
  • How do you sample a permutation uniformly at random in linear time, and why does swapping every index with a random index across the full array introduce bias? Use the Fisher–Yates shuffle (an in-place pass that picks one random remaining item per slot): loop i from n - 1 down to 1, pick j uniformly in [0, i] inclusive, and swap a[i] with a[j]. That makes n * (n - 1) * ... * 2 = n! equally likely choice sequences, mapping 1-to-1 onto the n! permutations in O(n) time (1 / n! probability each). The naive loop that picks j in [0, n - 1] at every index i produces n^n equally likely paths; for n >= 3, n^n is not divisible by n! (since n - 1 divides n! and shares no prime factor with n), biasing outcomes — on [1, 2, 3], 3^3 = 27 paths give 132, 213, and 231 probability 5/27 each while 123, 312, and 321 get 4/27 each.

```python import random

def fisher_yates_shuffle(items): a = list(items) for i in range(len(a) - 1, 0, -1): j = random.randint(0, i) # uniform in [0, i], inclusive a[i], a[j] = a[j], a[i] return a ```

  • How can you compute the k-th dictionary permutation directly without stepping through the k preceding arrangements? Express k (0 <= k < n!) in the factorial number system — a mixed-base representation where position m from the right has place value m!. Among the n! lexicographic permutations of n sorted distinct items, each choice for index 0 spans a contiguous block of (n - 1)! permutations, so index 0 must pick remaining[k // (n - 1)!]; remove that item, update k = k % (n - 1)!, and repeat on the remaining n - 1 items. For [1, 2, 3, 4] and k = 9: 9 // 6 = 1 picks 2 (k = 3), 3 // 2 = 1 picks 3 from [1, 3, 4] (k = 1), 1 // 1 = 1 picks 4 from [1, 4] (k = 0), leaving 1 -> [2, 3, 4, 1], taking O(n²) time with list pops (or O(n log n) using a Fenwick tree, a compact prefix-sum array that finds and removes the d-th remaining item in O(log n) time).

```python from math import factorial

def kth_permutation(items, k): remaining = sorted(items) result = [] while remaining: block_size = factorial(len(remaining) - 1) choice_index = k // block_size k = k % block_size result.append(remaining.pop(choice_index)) return result ```

  • Why can an unconstrained sorting routine be slowed down without bound, and what model assumption makes the 'slowest' sort well defined? Prepending a finite loop of f(n) dummy operations (such as counting to 2^(2^n) or sorting the array f(n) times) keeps any sort correct while making it slower than any chosen bound, so no unconstrained worst exists. A meaningful rule must require progress without wasted repetition: under "only inspect values via is_sorted(arrangement) and never test an arrangement twice," the tight worst case is n! tests (achieved by permutation sort). Interestingly, changing the allowed primitive changes the answer: under "only ask pairwise comparisons a <= b and never ask a comparison already implied by earlier answers," there are only n(n - 1) / 2 pairs in total, showing that permutation sort's n! cost comes from discarding partial ordering clues between failed is_sorted checks.

Follow-up questions

Similar questions

More Mercor interview questions

All 44 Mercor questions →