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:
- 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. - Exact single-pass permutation generation: Describe an algorithm that enumerates every permutation of
nelements 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 andis_sortedverification 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
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 to2^(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! · ...)).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
ninput items one at a time without repeats. 2. Check each candidate withis_sorted(at mostn - 1adjacent 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 TrueWhy 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, sois_sortedis guaranteed to returnTruewithin at mostn!checks.Running-time derivation: - How many candidates: Slot
0hasnchoices, slot1hasn - 1remaining choices, down to1choice for slotn - 1, givingn * (n - 1) * ... * 1 = n!index permutations. - Cost per candidate: Building a candidate list of lengthntakesΘ(n)time, andis_sortedtakesO(n)time (n - 1comparisons when sorted, and on average fewer than2comparisons when unsorted because the first pair already fails half the time). - Total worst-case time —Θ(n · n!): Materializing and testing up ton!candidates costsΘ(n · n!)(orΘ(n!)if we step an index array in place in amortizedO(1)time and checkvalues[order[i]] <= values[order[i + 1]]without copying). - Average-case time —Θ(n · n!): On a random ordering ofndistinct items, the sorted arrangement is equally likely to sit at any of then!positions in our enumeration, averaging(n! + 1) / 2candidates.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)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 candidateHow bogosort's guarantees differ from permutation sort: - Expected running time —
Θ(n · n!): Forndistinct elements, each uniformΘ(n)shuffle lands on the unique sorted order with probability1 / n!. Waiting for an event of probabilityp = 1 / n!takes1 / 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) / 2average). - 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. Aftertshuffles, the probability of still being unsorted is(1 - 1 / n!)^t, which is strictly greater than0for every finitet. Bogosort terminates with probability 1, not with deterministic certainty.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]because1 < 2at index0). For[1, 2, 3], the3! = 6arrangements 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 TruePart 2b: Why every permutation appears once, and what it costs
Why every arrangement is produced once and only once: - Because every element after
isatisfiesa[k] >= a[k + 1], the suffixa[i + 1..]is already in descending order — no arrangement sharing the prefixa[0..i]can be dictionary-larger. - Therefore, the very next arrangement must increase indexiby the smallest available amount (swapping in the rightmosta[j] > a[i]) and then makea[i + 1..]as small as possible (reversing the still-descending suffix into ascending order). - Becausenext_permutationjumps 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 untilFalsevisits 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 ofn!steps. Long descending suffixes are rare: half of all permutations end witha[n - 2] < a[n - 1](suffix length1), only1 / 2!have a descending suffix of length>= 2,1 / 3!have length>= 3, and in general1 / k!have length>= k. Summing1/1! + 1/2! + 1/3! + ...bounds the average suffix length ate - 1 ≈ 1.72elements! - Total time:Θ(n!)to step in place through alln!arrangements, orΘ(n · n!)if you copy or print a length-nlist at every step. - Extra space —O(1): Everything happens in place via swaps ona.Part 2c: Repeated values and alternative generators
What happens when the input has repeated values: - Notice the strict inequalities
a[i] < a[i + 1]anda[j] > a[i]innext_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_permutationproduces[1, 1, 2] -> [1, 2, 1] -> [2, 1, 1]and then returnsFalse— visiting each distinct arrangement once (3! / 2! = 3instead of6). In general, if values have multiplicitiesc1, c2, ..., starting from ascending order produces alln! / (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 andO(n)extra space,Θ(n · n!)total time). To avoid duplicates on repeated values, sort first and skipkwhena[k] == a[k - 1]andnot used[k - 1]. - Heap's algorithm: Steps through alln!arrangements so that each consecutive arrangement differs by just one swap (O(n!)total swaps,O(n)state array, non-lexicographic order).Part 2d: Plug the generator into permutation sort and stop early
There is a crucial trap when connecting
next_permutationtopermutation_sort: permute the index arrayorder = [0, 1, ..., n - 1], notvaluesitself! Why? 1. Runningnext_permutationdirectly onvaluescomparesvalues[i]withvalues[i + 1], violating our black-boxis_sorted-only rule — in fact, steppingvaluesuntilnext_permutationreturnsFalsereversesvaluesinto sorted order without ever callingis_sorted! 2. Worse, startingnext_permutationon an arbitraryvalueslike[3, 2, 1]stops after 1 step without ever visiting[1, 2, 3]unless you sortvaluesfirst (which begs the question!).Permuting
order = [0, 1, ..., n - 1]solves both problems cleanly:0, 1, ..., n - 1already starts in ascending order without inspectingvalues, visits alln!rearrangements ofvalues, and stops the instantis_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]) passesis_sortedimmediately. - Worst case —
Θ(n · n!): On a reversed input of distinct values[3, 2, 1], the sorted order requiresorder = [2, 1, 0]— the very last of then!index orders — checking every candidate. - Extra space —
O(n): Onlyorderand the currentcandidatelist are held in memory at any moment.
- Early stopping (best case) —
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 atn!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 then!index permutations; building a length-ncandidate and runningis_sortedcostsΘ(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_permutationsteps inO(1)amortized time andO(1)extra space: Finding the rightmost ascenta[i] < a[i + 1], swappinga[i]with the rightmosta[j] > a[i], and reversinga[i + 1..]produces the immediate dictionary successor; amortized (averaged across alln!steps) suffix length is1/1! + 1/2! + ... ≈ e - 1 ≈ 1.72.- Repeated values collapse cleanly under strict
<and>: Starting from sorted values with multiplicitiesc1, c2, ...,next_permutationemits each of then! / (c1! · c2! · ...)distinct value arrangements once, whereasitertools.permutationsand plain backtracking emit duplicate value tuples unless filtered. - Permute indices, not values, inside permutation sort: Running
next_permutationonorder = [0, 1, ..., n - 1]starts in ascending order automatically without comparing input values outsideis_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 (∞), notO(n!). - Claiming bogosort is guaranteed to terminate: Terminating with probability 1 is weaker than deterministic termination — the failure sequence
(1 - 1 / n!)^tstays positive for every finitet. - Forgetting the
Θ(n)copy cost per permutation: Materializing a new tuple or list of lengthnon each ofn!steps givesΘ(n · n!)total work;Θ(n!)holds only when stepping in place and checkingvalues[order[i]] <= values[order[i + 1]]with early exit. - Storing a
seenset of permutations in memory: Saving previously generated permutations requiresΘ(n · n!)RAM (> 36million ints already atn = 10), whereasnext_permutationneedsO(1)extra space. - Starting value-based
next_permutationon an unsorted array: Callingnext_permutationdirectly 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
ndistinct elements, eachΘ(n)uniform shuffle hits the unique sorted order with probability1 / n!. That trial count follows a geometric distribution (number of independent coin flips of success probabilitypuntil the first heads, with mean1 / p), givingn!expected shuffles andΘ(n · n!)expected time (faster when duplicate values exist, sincec1! · c2! · ...arrangements are sorted). It is not guaranteed to terminate: mathematically(1 - 1 / n!)^t > 0for everyt, and in practice a pseudo-random number generator (PRNG) — a deterministic state machine mimicking randomness — has finitely many internal states (Python's Mersenne Twister has2^19937 - 1states, which is smaller thann!oncen >= 2081, so most permutations of2081items can never even be produced byrandom.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
ifromn - 1down to1, pickjuniformly in[0, i]inclusive, and swapa[i]witha[j]. That makesn * (n - 1) * ... * 2 = n!equally likely choice sequences, mapping1-to-1onto then!permutations inO(n)time (1 / n!probability each). The naive loop that picksjin[0, n - 1]at every indexiproducesn^nequally likely paths; forn >= 3,n^nis not divisible byn!(sincen - 1dividesn!and shares no prime factor withn), biasing outcomes — on[1, 2, 3],3^3 = 27paths give132,213, and231probability5/27each while123,312, and321get4/27each.
```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 thekpreceding arrangements? Expressk(0 <= k < n!) in the factorial number system — a mixed-base representation where positionmfrom the right has place valuem!. Among then!lexicographic permutations ofnsorted distinct items, each choice for index0spans a contiguous block of(n - 1)!permutations, so index0must pickremaining[k // (n - 1)!]; remove that item, updatek = k % (n - 1)!, and repeat on the remainingn - 1items. For[1, 2, 3, 4]andk = 9:9 // 6 = 1picks2(k = 3),3 // 2 = 1picks3from[1, 3, 4](k = 1),1 // 1 = 1picks4from[1, 4](k = 0), leaving1->[2, 3, 4, 1], takingO(n²)time with list pops (orO(n log n)using a Fenwick tree, a compact prefix-sum array that finds and removes thed-th remaining item inO(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 to2^(2^n)or sorting the arrayf(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 viais_sorted(arrangement)and never test an arrangement twice," the tight worst case isn!tests (achieved by permutation sort). Interestingly, changing the allowed primitive changes the answer: under "only ask pairwise comparisonsa <= band never ask a comparison already implied by earlier answers," there are onlyn(n - 1) / 2pairs in total, showing that permutation sort'sn!cost comes from discarding partial ordering clues between failedis_sortedchecks.
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?
- 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?
- How can you compute the `k`-th dictionary permutation directly without stepping through the `k` preceding arrangements?
- Why can an unconstrained sorting routine be slowed down without bound, and what model assumption makes the 'slowest' sort well defined?
Similar questions
- Retry-Safe Ticket Checkout Across External Payments
- Reviewing a Ride-Fare Capture and Trip-Logging Method
- Reviewing a Python Dictionary Memoization Snippet
- Reviewing and Hardening a Java CSV Formatter
- Code Review: Mid-Call Failure in a Charge-Then-Insert Payment Service
- Multi-Threaded Review of a Python Lookup-and-Compute Cache
More Mercor interview questions
- Designing and Analyzing the Slowest Correct Sorting Procedure Medium
- Sub-Quadratic Sorting, Quicksort Pitfalls, and Super-Quadratic Permutations Medium
- Code Review: Mid-Call Failure in a Charge-Then-Insert Payment Service Medium Pro
- Intentionally Slow Sorting Algorithm and Runtime Analysis Easy Pro
- Designing a Crash- and Retry-Safe External Payment Endpoint Medium Pro
- Thread-Safe Function Memoizer Under Concurrent Load Medium Pro
- Winning Probability Between Two Random Pairs Medium Pro
- RFC 4180 CSV Serialization and Lazy Row Streaming Medium Pro
- Idempotent Checkout Charging and Payment Persistence with Stripe Medium Pro
- Defending True Project Ownership Versus Contribution Medium Pro