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

  1. 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 to 2 ** (2 ** n) first — meaning no single "worst" algorithm could ever exist.

    Start your answer by stating three ground rules:

    1. 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).
    2. 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.
    3. 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.

  2. 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 n input positions 0, 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 passes is_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 > 1 tells Insertion Sort or Merge Sort to keep 1 ahead of 3 forever). Permutation sort forgets immediately and blindly tries the next rearrangement from scratch.

    Here is the exact trace on values = [3, 1, 2] (3! = 6 position 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)
    
  3. 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):

    1. At least one sorted permutation exists: because the elements obey a total order (any two items can be compared consistently with <=, and a <= b plus b <= c implies a <= c), repeatedly picking a smallest remaining item constructs a valid non-decreasing ordering of the n input positions.
    2. Finite search space: an input of length n has a factorial number of position orderings, written n! = 1 * 2 * ... * n (with 0! = 1 for the empty list []). Because the enumeration visits every position ordering without repeats and each is_sorted check performs at most n - 1 comparisons, the loop must hit a sorted candidate within at most n! iterations.
    3. Exact elements and order: the returned list came directly from rearranging the n input positions (preserving every element and its exact duplicate count) and passed is_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.

  4. Count how many candidates get checked

    How many of the n! candidates does permutation sort inspect before stopping?

    • Best case — 1 candidate: if the input is already sorted (for example [1, 2, 3, 4]), the very first position order (0, 1, 2, ..., n - 1) passes is_sorted immediately after n - 1 comparisons.
    • Worst case — all n! candidates: if the input consists of n distinct 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 the n! 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 rank 96 of 5! = 120, skipping the final 24 candidates.)
    • Average case — (n! + 1) / 2 candidates: over a uniformly random ordering of n distinct values, the unique sorting position permutation is equally likely to sit at any rank 1, 2, ..., n!, whose average is (1 + n!) / 2.

    n! outgrows every polynomial n^k and every exponential c^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
    
  5. Compute the exact cost per candidate

    Total runtime equals (number of candidates) * (cost to build + cost to check one candidate).

    At first glance, is_sorted looks like it costs O(n) comparisons per candidate. In the worst case, however, is_sorted stops at the very first drop! Watch all 3! = 6 permutations 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 average
    

    Why 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 first 2 items were in order (1/2! = 1/2 of candidates).
    • Comparison #3 (i = 2) only runs if the first 3 items were in order (1/3! = 1/6 of candidates).
    • Comparison #k only runs if the first k items 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 (about 1.718 comparisons 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 uses Theta(n * n!) RAM (479 million tuples at n = 12), crashing with out-of-memory long before the CPU finishes.

  6. Generate permutations lazily in O(n) space

    To hit Theta(n!) worst-case time in O(n) extra memory, keep a single position array order = [0, 1, ..., n - 1] and advance it in place using the classic 4-step next_permutation algorithm:

    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_permutation amortized O(1) (meaning its average cost per step over the full n! run is bounded by a constant, even though a single step can reverse up to n elements)? For the exact same factorial reason as is_sorted: reversing a tail of length k happens only once every k! steps, so total work across all n! 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 result
    

    Notice why we permute indices 0..n-1 rather than permuting values directly: if you called next_permutation on values itself and wrapped around at the end (as C++ std::next_permutation does), 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.

  7. Check practical scaling limits on real hardware

    How big can n get before n! hits a wall? On a typical laptop, CPython's C-backed itertools.permutations loop checks roughly 9 million candidates per second (~0.4 s for 10! = 3.63 million), while an optimistic compiled C/Rust loop might check 1 billion (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 years
    

    Notice two practical takeaways:

    • In Python, permutation_sort with itertools.permutations (Theta(n * n!)) actually beats permutation_sort_in_place (Theta(n!)) for small n because itertools runs in compiled C while next_permutation executes Python bytecode; the Theta(n!) advantage shows up in compiled languages.
    • Faster hardware barely moves the needle on factorial growth: around n = 13, buying a computer 1,000x faster only increases the feasible input size by 2 elements (14 * 15 = 210 fits inside 1,000x, while 14 * 15 * 16 = 3,360 already exceeds it).

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):

  1. Candidate 1 — positions (0, 1, 2) -> [3, 1, 2]: check index 0 (3 > 1), fails immediately after 1 comparison.
  2. Candidate 2 — positions (0, 2, 1) -> [3, 2, 1]: check index 0 (3 > 2), fails immediately after 1 comparison.
  3. Candidate 3 — positions (1, 0, 2) -> [1, 3, 2]: 1 <= 3 passes, then 3 > 2 fails after 2 comparisons.
  4. Candidate 4 — positions (1, 2, 0) -> [1, 2, 3]: 1 <= 2 and 2 <= 3 both 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 most n! finite candidates so it must reach one; and any returned candidate is a position rearrangement that passed is_sorted.
  • Best, average, and worst candidate counts. Best case checks 1 candidate (already sorted input, Theta(n) time to verify); worst case checks all n! 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) / 2 candidates.
  • Per-candidate cost separates Theta(n * n!) from Theta(n!). Because is_sorted exits at the first drop, it averages 1/1! + 1/2! + ... + 1/(n - 1)! < e - 1 (about 1.72, O(1)) comparisons per candidate over a full run. Allocating a fresh tuple per candidate costs Theta(n) (Theta(n * n!) total), whereas advancing an index array in place with next_permutation costs amortized O(1) (constant average work per step across the full run), giving Theta(n!) worst-case time and O(n) extra space.
  • Hard feasibility wall around n = 12 to 15. Because 13! = 6.23 billion and 20! = 2.43 * 10^18, even a billion candidates per second takes ~22 minutes at n = 15 and ~77 years at n = 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 within n! 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 an n-element tuple for each candidate and checking all elements without early exit makes worst-case time Theta(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_sorted still has to inspect all n - 1 adjacent 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 before n! (for example, [4, 3, 2, 1, 1] hits sorted position order (3, 4, 2, 1, 0) at candidate 96 of 120).
  • Calling list(permutations(values)) in memory. Storing all candidates upfront requires Theta(n * n!) memory and crashes RAM around n = 11 or 12.

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 with next_permutation: find the rightmost index i where order[i] < order[i + 1], swap order[i] with the rightmost larger entry to its right, and reverse the tail after i. A single transition can touch O(n) elements in the worst case, but because a tail of length k is reversed only once every k! steps, the cost across a full enumeration is O(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 n distinct elements, each uniform random shuffle (Fisher-Yates, Theta(n) per shuffle) succeeds with probability 1 / n!, following a geometric distribution (the count of independent trials until the first success) with expected n! shuffles and Theta(n * n!) expected time — whereas permutation sort never repeats a failed arrangement, checks (n! + 1) / 2 candidates on average, and with in-place generation takes Theta(n!) expected time. Furthermore, only permutation sort has a bounded worst case (n! candidates); random shuffling has probability (1 - 1 / n!)^k > 0 of exceeding any step count k.
  • 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 all n^n length-n index sequences with replacement (10^10 candidates at n = 10 instead of 3.63 million) 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" (making n! candidates tight), or "every step compares two elements whose order is not yet implied by transitivity" (capping any algorithm at n * (n - 1) / 2 comparisons, a game famously explored by Broder and Stolfi's Slowsort, whose divide-and-surrender recurrence grows as n^(Theta(log n))).
  • At roughly what input length n does this approach hit a practical wall on contemporary hardware? Because n! jumps from 4.79 * 10^8 at n = 12 to 6.23 * 10^9 at n = 13, 1.31 * 10^12 at n = 15, and 2.43 * 10^18 at n = 20, the practical ceiling is roughly n = 12 to 13 in an interpreted language like Python (~1 to 12 minutes in the worst case) and n = 14 to 15 in optimized compiled C or Rust (~22 minutes at 10^9 candidates/sec for n = 15). Each additional item multiplies runtime by n, so even a 1,000x speedup from faster hardware or parallelism adds only about 2 extra elements to the limit.

Follow-up questions

Similar questions

More Mercor interview questions

All 44 Mercor questions →