Designing and Analyzing the Slowest Correct Sorting Procedure
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
Engineering interviews typically ask how quickly you can sort n items. Flip that objective on its head: devise the slowest, least efficient sorting procedure you can justify that remains strictly valid — guaranteed to halt on every input and output the elements in non-decreasing order.
Assume the input holds n elements drawn from a totally ordered domain where duplicate values may appear. Walk through how your procedure operates, prove that it always finishes with a validly sorted arrangement, and derive its time and space bounds. Make sure to clarify any ground rules needed up front — such as ruling out arbitrary busy-work (sleep calls or empty loops), requiring deterministic worst-case termination vs. probabilistic completion, and distinguishing best, average, and worst cases.
Scope & Expectations
- Well-posed problem framing: State clear rules forbidding artificial stalling so every operation genuinely constructs or verifies candidate orderings.
- Algorithm & correctness: Present a concrete deterministic procedure, handle duplicate elements cleanly, and prove both finite termination and sorted output.
- Candidate & per-step complexity: Derive best-case, average-case, and worst-case candidate counts alongside the per-candidate generation and verification cost and auxiliary memory footprint.
- Practical scaling intuition: Relate factorial growth to realistic input sizes and contrast deterministic search against randomized shuffling.
Step-by-step walkthrough
Set clear ground rules so "worst" is well defined
Asking for "the worst sorting algorithm" is a trick question until you outlaw artificial padding. If useless work were allowed, you could take any sorting algorithm and insert
sleep(10 ** n)or count to2 ** (2 ** n)first — meaning no single "worst" algorithm could ever exist.Start your answer by stating three ground rules:
- Guaranteed deterministic termination: the algorithm must finish in a finite, bounded number of steps on every valid input (unlike purely random shuffling, which can theoretically run forever).
- No artificial padding: every action must genuinely participate in finding the sorted output by either constructing a distinct candidate arrangement or testing whether that arrangement is sorted.
- Full complexity breakdown: analyze best-case, average-case, and worst-case time alongside extra memory space.
Under these rules, the goal becomes clear: design a search that throws away all structural clues from failed comparisons while still guaranteeing it eventually visits the sorted order.
Design the algorithm: exhaustive permutation sort
A sorted list is just one rearrangement of the input positions that happens to be in non-decreasing order (
a[0] <= a[1] <= ... <= a[n - 1]). Checking whether one candidate arrangement is sorted takes a single left-to-right scan.Permutation sort uses pure generate-and-test: enumerate every permutation (one specific ordering of the
ninput positions0, 1, ..., n - 1) in lexicographic order (dictionary order, comparing two position lists from left to right at the first index where they differ), and return the very first candidate that passesis_sorted:from itertools import permutations def is_sorted(values): """Return True if values is in non-decreasing order, stopping at the first drop.""" for i in range(len(values) - 1): if values[i] > values[i + 1]: return False return True def permutation_sort(values): """Try every position permutation in dictionary order and return the first sorted one.""" for candidate in permutations(values): if is_sorted(candidate): return list(candidate) return []Why is this so slow? Normal sorting algorithms remember every comparison (
3 > 1tells Insertion Sort or Merge Sort to keep1ahead of3forever). Permutation sort forgets immediately and blindly tries the next rearrangement from scratch.Here is the exact trace on
values = [3, 1, 2](3! = 6position permutations total):Position order Candidate values Check (left to right) Outcome -------------- ---------------- ---------------------------- ------- 1. (0, 1, 2) (3, 1, 2) 3 > 1 at index 0 reject 2. (0, 2, 1) (3, 2, 1) 3 > 2 at index 0 reject 3. (1, 0, 2) (1, 3, 2) 1 <= 3 ok; 3 > 2 at index 1 reject 4. (1, 2, 0) (1, 2, 3) 1 <= 2 ok; 2 <= 3 ok SORTED -> return [1, 2, 3] (candidates 5 and 6 are never reached)Prove termination and correctness (including duplicates)
Correctness requires proving both partial correctness (if it returns, the answer is a sorted rearrangement of the input) and termination (it always returns in finite steps):
- At least one sorted permutation exists: because the elements obey a total order (any two items can be compared consistently with
<=, anda <= bplusb <= cimpliesa <= c), repeatedly picking a smallest remaining item constructs a valid non-decreasing ordering of theninput positions. - Finite search space: an input of length
nhas a factorial number of position orderings, writtenn! = 1 * 2 * ... * n(with0! = 1for the empty list[]). Because the enumeration visits every position ordering without repeats and eachis_sortedcheck performs at mostn - 1comparisons, the loop must hit a sorted candidate within at mostn!iterations. - Exact elements and order: the returned list came directly from rearranging the
ninput positions (preserving every element and its exact duplicate count) and passedis_sorted(candidate[i] <= candidate[i + 1]for every adjacent pair).
Duplicates are handled automatically: if multiple position permutations produce the sorted output (for instance, swapping two equal
1s), every one of them equals the exact same sorted list, and returning the first one encountered is completely valid.- At least one sorted permutation exists: because the elements obey a total order (any two items can be compared consistently with
Count how many candidates get checked
How many of the
n!candidates does permutation sort inspect before stopping?- Best case —
1candidate: if the input is already sorted (for example[1, 2, 3, 4]), the very first position order(0, 1, 2, ..., n - 1)passesis_sortedimmediately aftern - 1comparisons. - Worst case — all
n!candidates: if the input consists ofndistinct values in strictly decreasing order (for example[4, 3, 2, 1]), the unique sorted position order is(n - 1, n - 2, ..., 0), which is the very last entry in lexicographic order. Every single one of then!permutations is tested. (When duplicates exist, multiple position orders are sorted so the worst case stops earlier: for[4, 3, 2, 1, 1],(3, 4, 2, 1, 0)is sorted at rank96of5! = 120, skipping the final24candidates.) - Average case —
(n! + 1) / 2candidates: over a uniformly random ordering ofndistinct values, the unique sorting position permutation is equally likely to sit at any rank1, 2, ..., n!, whose average is(1 + n!) / 2.
n!outgrows every polynomialn^kand every exponentialc^n:n n! (worst-case candidates) --- ------------------------------------------------ 5 120 10 3,628,800 12 479,001,600 13 6,227,020,800 15 1,307,674,368,000 20 2,432,902,008,176,640,000- Best case —
Compute the exact cost per candidate
Total runtime equals
(number of candidates) * (cost to build + cost to check one candidate).At first glance,
is_sortedlooks like it costsO(n)comparisons per candidate. In the worst case, however,is_sortedstops at the very first drop! Watch all3! = 6permutations of[1, 2, 3]:Candidate Comparisons run before stopping Count --------- ------------------------------- ----- (1, 2, 3) 1 <= 2, then 2 <= 3 2 (1, 3, 2) 1 <= 3, then 3 > 2 (stop!) 2 (2, 1, 3) 2 > 1 (stop!) 1 (2, 3, 1) 2 <= 3, then 3 > 1 (stop!) 2 (3, 1, 2) 3 > 1 (stop!) 1 (3, 2, 1) 3 > 2 (stop!) 1 --------------------------------------------------- Total = 9 comparisons across 6 candidates -> 9 / 6 = 1.50 comparisons on averageWhy is it so small? Across all
n!arrangements of distinct items:- Comparison #1 (
i = 0) always runs (1 = 1/1!of candidates). - Comparison #2 (
i = 1) only runs if the first2items were in order (1/2! = 1/2of candidates). - Comparison #3 (
i = 2) only runs if the first3items were in order (1/3! = 1/6of candidates). - Comparison #k only runs if the first
kitems were in order (1/k!of candidates).
Summing
1/1! + 1/2! + 1/3! + ... + 1/(n - 1)!is strictly bounded above by Euler's constant minus one:e - 1(about1.718comparisons per candidate on average, O(1))!So the bottleneck per candidate is actually how candidates are produced:
Implementation Build 1 candidate Check (avg) Worst-case time Extra space ---------------------------------- ----------------- ----------- --------------- ----------- Copy a fresh n-tuple each step Theta(n) O(1) Theta(n * n!) O(n) Advance an index array in place O(1) amortized O(1) Theta(n!) O(n) Best case (input already sorted) Theta(n) n - 1 Theta(n) O(n)Never write
list(permutations(values))first: materializing all candidates at once usesTheta(n * n!)RAM (479million tuples atn = 12), crashing with out-of-memory long before the CPU finishes.- Comparison #1 (
Generate permutations lazily in O(n) space
To hit
Theta(n!)worst-case time inO(n)extra memory, keep a single position arrayorder = [0, 1, ..., n - 1]and advance it in place using the classic 4-stepnext_permutationalgorithm:Example: advance order = [0, 2, 3, 1] to the very next dictionary permutation 1. Scan left from the end for the rightmost climb order[i] < order[i + 1]: [0, 2, 3, 1] -> climb is 2 < 3 at i = 1 (suffix [3, 1] is non-increasing) ^ 2. Scan left from the end for the rightmost element larger than order[i] = 2: [0, 2, 3, 1] -> 3 > 2 at j = 2 ^ 3. Swap order[i] and order[j]: [0, 3, 2, 1] 4. Reverse the suffix after i to make it as small as possible: [0, 3, 1, 2] -> next permutation!Why is
next_permutationamortized O(1) (meaning its average cost per step over the fulln!run is bounded by a constant, even though a single step can reverse up tonelements)? For the exact same factorial reason asis_sorted: reversing a tail of lengthkhappens only once everyk!steps, so total work across alln!steps is< (e - 1) * n!.def next_permutation(order): """Advance `order` in place to the next lexicographic permutation, or return False at the end.""" # Step 1: find rightmost index i where order[i] < order[i + 1] (using >= handles duplicates safely). i = len(order) - 2 while i >= 0 and order[i] >= order[i + 1]: i -= 1 if i < 0: return False # Step 2: find rightmost index j > i with order[j] > order[i]. j = len(order) - 1 while order[j] <= order[i]: j -= 1 # Step 3 & 4: swap pivot with successor, then reverse the non-increasing suffix in place. order[i], order[j] = order[j], order[i] left = i + 1 right = len(order) - 1 while left < right: order[left], order[right] = order[right], order[left] left += 1 right -= 1 return True def sorted_under(values, order): """Check whether reading `values` in `order` produces a non-decreasing sequence.""" for k in range(len(order) - 1): if values[order[k]] > values[order[k + 1]]: return False return True def permutation_sort_in_place(values): """Sort `values` in Theta(n!) worst-case time and O(n) extra space.""" order = list(range(len(values))) while not sorted_under(values, order): next_permutation(order) result = [] for index in order: result.append(values[index]) return resultNotice why we permute indices
0..n-1rather than permutingvaluesdirectly: if you callednext_permutationonvaluesitself and wrapped around at the end (as C++std::next_permutationdoes), a strictly decreasing list[4, 3, 2, 1]would wrap straight to[1, 2, 3, 4]in one step! Permuting indices keeps the search genuinely blind to the input values.Check practical scaling limits on real hardware
How big can
nget beforen!hits a wall? On a typical laptop, CPython's C-backeditertools.permutationsloop checks roughly9million candidates per second (~0.4 sfor10! = 3.63million), while an optimistic compiled C/Rust loop might check1billion (10^9) candidates per second:n Worst-case n! CPython (~9M / sec) Optimistic C/Rust (~1B / sec) --- ------------- ------------------- ----------------------------- 10 3.63e6 ~0.4 seconds ~4 milliseconds 12 4.79e8 ~53 seconds ~0.5 seconds 13 6.23e9 ~11.5 minutes ~6 seconds 15 1.31e12 ~1.7 days ~22 minutes 17 3.56e14 ~1.3 years ~4 days 20 2.43e18 ~8,600 years ~77 yearsNotice two practical takeaways:
- In Python,
permutation_sortwithitertools.permutations(Theta(n * n!)) actually beatspermutation_sort_in_place(Theta(n!)) for smallnbecauseitertoolsruns in compiled C whilenext_permutationexecutes Python bytecode; theTheta(n!)advantage shows up in compiled languages. - Faster hardware barely moves the needle on factorial growth: around
n = 13, buying a computer1,000xfaster only increases the feasible input size by2elements (14 * 15 = 210fits inside1,000x, while14 * 15 * 16 = 3,360already exceeds it).
- In Python,
Intuition & how it works
Imagine opening a briefcase with a combination lock by dialing 000, pulling the latch, dialing 001, pulling the latch, and marching blindly through every single combination in order without ever listening to the clicks. Permutation sort applies that exact idea to sorting: instead of learning from comparisons to move items closer to sorted order, it lists every permutation (every distinct ordering of the n input positions 0, 1, ..., n - 1) in lexicographic order (dictionary order from left to right) and returns the first candidate that happens to be non-decreasing.
Two common first instincts fall short in interviews. Answering "add sleep(10 ** n) to Merge Sort" is artificial padding rather than an algorithm, and since you could always sleep longer, no "worst" algorithm would exist. Answering "Bogosort — shuffle randomly until sorted" has no worst-case upper bound because bad coin flips can repeat unsorted shuffles indefinitely, violating strict worst-case termination.
Here is how permutation sort works on values = [3, 1, 2] (3! = 6 possible position orders):
- Candidate 1 — positions
(0, 1, 2)->[3, 1, 2]: check index0(3 > 1), fails immediately after 1 comparison. - Candidate 2 — positions
(0, 2, 1)->[3, 2, 1]: check index0(3 > 2), fails immediately after 1 comparison. - Candidate 3 — positions
(1, 0, 2)->[1, 3, 2]:1 <= 3passes, then3 > 2fails after 2 comparisons. - Candidate 4 — positions
(1, 2, 0)->[1, 2, 3]:1 <= 2and2 <= 3both pass — stop and return[1, 2, 3].
Key points
- State fair ground rules first. Require deterministic termination and forbid artificial padding (every step must either build a distinct candidate arrangement or check whether it is sorted) so the question is mathematically well defined.
- Exhaustive generate-and-test. Enumerating position permutations in dictionary order ignores all information from failed comparisons, giving factorial (
n! = 1 * 2 * ... * n) candidate counts while guaranteeing termination. - Three-step correctness proof. Under any total order (consistent
<=comparisons across all elements), at least one sorted arrangement exists; the search checks at mostn!finite candidates so it must reach one; and any returned candidate is a position rearrangement that passedis_sorted. - Best, average, and worst candidate counts. Best case checks
1candidate (already sorted input,Theta(n)time to verify); worst case checks alln!candidates (distinct values in strictly decreasing order, whose sorted position order(n - 1, ..., 0)comes last); average case on random distinct values checks(n! + 1) / 2candidates. - Per-candidate cost separates
Theta(n * n!)fromTheta(n!). Becauseis_sortedexits at the first drop, it averages1/1! + 1/2! + ... + 1/(n - 1)! < e - 1(about1.72,O(1)) comparisons per candidate over a full run. Allocating a fresh tuple per candidate costsTheta(n)(Theta(n * n!)total), whereas advancing an index array in place withnext_permutationcosts amortized O(1) (constant average work per step across the full run), givingTheta(n!)worst-case time andO(n)extra space. - Hard feasibility wall around
n = 12to15. Because13! = 6.23billion and20! = 2.43 * 10^18, even a billion candidates per second takes~22minutes atn = 15and~77years atn = 20.
Common mistakes
- Proposing Bogosort without noting unbounded worst-case time. Random shuffling finishes with probability
1, but any finite step bound can be exceeded with positive probability; deterministic permutation sort guarantees stopping withinn!candidates. - Padding a fast sort with
sleep()or dummy loops. That dodges algorithmic analysis rather than designing an inefficient search strategy. - Saying "permutation sort is
O(n!)" while copying whole arrays. Copying ann-element tuple for each candidate and checking all elements without early exit makes worst-case timeTheta(n * n!);Theta(n!)requires both early-exit checking and an in-place generator. - Claiming best-case time is
O(1). Even when the first candidate is already sorted,is_sortedstill has to inspect alln - 1adjacent pairs (Theta(n)). - Confusing position permutations with distinct value permutations on duplicates. There are always
n!position orders, and duplicates create multiple winning candidates so the worst case finishes beforen!(for example,[4, 3, 2, 1, 1]hits sorted position order(3, 4, 2, 1, 0)at candidate96of120). - Calling
list(permutations(values))in memory. Storing all candidates upfront requiresTheta(n * n!)memory and crashes RAM aroundn = 11or12.
Follow-up questions
- How can you stream candidate arrangements one by one without keeping all of them in memory, and how much work does each step take? Keep one array of indices
order = [0, 1, ..., n - 1](O(n)extra space) and transform it in place withnext_permutation: find the rightmost indexiwhereorder[i] < order[i + 1], swaporder[i]with the rightmost larger entry to its right, and reverse the tail afteri. A single transition can touchO(n)elements in the worst case, but because a tail of lengthkis reversed only once everyk!steps, the cost across a full enumeration isO(1)amortized per candidate (Heap's algorithm achieves the same goal using a single swap per step). - How does your deterministic approach compare against repeatedly shuffling at random until sorted in terms of expected runtime and worst-case termination? Permutation sort wins on both counts! On
ndistinct elements, each uniform random shuffle (Fisher-Yates,Theta(n)per shuffle) succeeds with probability1 / n!, following a geometric distribution (the count of independent trials until the first success) with expectedn!shuffles andTheta(n * n!)expected time — whereas permutation sort never repeats a failed arrangement, checks(n! + 1) / 2candidates on average, and with in-place generation takesTheta(n!)expected time. Furthermore, only permutation sort has a bounded worst case (n!candidates); random shuffling has probability(1 - 1 / n!)^k > 0of exceeding any step countk. - Since any routine could be slowed down artificially, what formal constraint makes asking for a 'slowest' sorting algorithm mathematically meaningful? Without strict rules, yes, any sort can be made slower: even without
sleep(), an algorithm could enumerate alln^nlength-nindex sequences with replacement (10^10candidates atn = 10instead of3.63million) and check whether each sequence is both a valid permutation and sorted, or encode candidates inside even larger search spaces. To make "the slowest sorting algorithm" mathematically well defined, restrict the computation model — for instance, "every step tests a distinct permutation of the input positions and halts on the first sorted one" (makingn!candidates tight), or "every step compares two elements whose order is not yet implied by transitivity" (capping any algorithm atn * (n - 1) / 2comparisons, a game famously explored by Broder and Stolfi's Slowsort, whose divide-and-surrender recurrence grows asn^(Theta(log n))). - At roughly what input length
ndoes this approach hit a practical wall on contemporary hardware? Becausen!jumps from4.79 * 10^8atn = 12to6.23 * 10^9atn = 13,1.31 * 10^12atn = 15, and2.43 * 10^18atn = 20, the practical ceiling is roughlyn = 12to13in an interpreted language like Python (~1to12minutes in the worst case) andn = 14to15in optimized compiled C or Rust (~22minutes at10^9candidates/sec forn = 15). Each additional item multiplies runtime byn, so even a1,000xspeedup from faster hardware or parallelism adds only about2extra elements to the limit.
Follow-up questions
- How can you stream candidate arrangements one by one without keeping all of them in memory, and how much work does each step take?
- How does your deterministic approach compare against repeatedly shuffling at random until sorted in terms of expected runtime and worst-case termination?
- Since any routine could be slowed down artificially, what formal constraint makes asking for a 'slowest' sorting algorithm mathematically meaningful?
- At roughly what input length `n` does this approach hit a practical wall on contemporary hardware?
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
- Sub-Quadratic Sorting, Quicksort Pitfalls, and Super-Quadratic Permutations Medium
- Factorial-Time Sorting and Exact Permutation Enumeration 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