Sub-Quadratic Sorting, Quicksort Pitfalls, and Super-Quadratic Permutations

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

In this conceptual discussion (no live coding required), you are analyzing sorting algorithms over an array of n mutually comparable elements, explicitly naming whether every runtime claim describes worst-case, average-case, or randomized expected behavior:

  1. Beating quadratic insertion sort: Basic insertion sort requires O(n^2) operations in the worst and average cases. Explain how to construct a sorting algorithm with strictly better asymptotic complexity, walk through its mechanism, and justify why its total work drops.
  2. Triggering and fixing quicksort's worst case: Identify a concrete pivot rule and input pattern that force quicksort into its worst-case runtime, derive that asymptotic cost, and discuss practical strategies that make the bad case improbable or impossible.
  3. Combinatorial counts and a super-quadratic sort: Treating the n array positions as distinct even when values repeat, derive (a) the number of non-empty subsequences (subsets of indices kept in original left-to-right order, contiguous or not) and (b) the number of full permutations. Using those counts, describe a valid, guaranteed-terminating sort whose runtime exceeds O(n^2) without artificial stalling, and state its complexity.

Scope & Expectations

  • Clear model & case labels: Distinguish comparison-based sorting from bounded-integer counting methods, and state whether every complexity bound is worst-case, average-case, or expected.
  • Sub-quadratic derivation: Explain a divide-and-conquer or heap-based sort step by step and justify O(n log n) via a recurrence relation or per-level work argument.
  • Unbalanced partitioning analysis: Show how 0 vs. m - 1 partition splits produce Theta(n^2) comparisons and compare randomized pivots, median-of-three, three-way partitioning, and introsort.
  • Combinatorics to factorial search: Derive both 2^n - 1 and n! from per-position choices, explain why permutations (not subsequences) enable sorting, and analyze deterministic permutation sort.

Step-by-step walkthrough

  1. Clarify the rules of the discussion

    Before diving into algorithms, settle the four clarifying questions because each one changes the exact bounds:

    • Comparison-based vs. integer keys: Assume a comparison-based sort — an algorithm that learns the relative order of elements only by asking pairwise questions like a <= b, without inspecting digits or using keys directly as array indices. Under this model, O(n log n) is the fastest possible worst-case time. (If keys are small integers in [0, k), counting sort tallies frequencies in an array of size k and runs in O(n + k) time, beating O(n log n) when k = O(n); mention this briefly, then focus on general comparison sorting.)
    • Which running-time case: Always state the case explicitly:
      • Worst case: the maximum work over all inputs of length n.
      • Average case: the average work over a uniformly random input ordering.
      • Expected time: the average work over the algorithm's own random choices on any fixed input (even an adversarial one).
    • Rules for the slower sort: It must still terminate on every input with a genuinely sorted result, and its slowness must come from how it searches for the sorted order — not from artificial padding like sleep() or empty busy-loops.
    • Counting duplicate values: Count index positions separately even when values repeat. For example, on [1, 1] at indices 0 and 1, choosing index {0}, {1}, or {0, 1} gives 3 non-empty subsequences, and ordering indices as (0, 1) or (1, 0) gives 2 permutations.
  2. Why insertion sort takes O(n²) time

    Insertion sort maintains a sorted prefix on the left and inserts one new element a[i] at a time by shifting larger elements one slot to the right.

    An inversion is a pair of positions i < j whose elements are out of order (a[i] > a[j]). Every adjacent shift in insertion sort swaps x past one larger neighbor to its left, which removes exactly one inversion:

    Input: [4, 3, 2, 1]   (all 6 pairs are inverted)
    
    i = 1 (x = 3): shift 4 right         -> [3, 4, 2, 1]   (1 shift)
    i = 2 (x = 2): shift 4, 3 right      -> [2, 3, 4, 1]   (2 shifts)
    i = 3 (x = 1): shift 4, 3, 2 right   -> [1, 2, 3, 4]   (3 shifts)
    Total shifts = 1 + 2 + 3 = 6 = 4 * 3 / 2
    
    def insertion_sort(a):
        result = list(a)
        for i in range(1, len(result)):
            current = result[i]
            j = i - 1
            # Each shift moves one larger element right and fixes one inversion
            while j >= 0 and result[j] > current:
                result[j + 1] = result[j]
                j -= 1
            result[j + 1] = current
        return result
    
    • Worst case — Θ(n²): On a strictly reversed array of length n, every pair of elements is inverted. There are n(n - 1) / 2 pairs (28 shifts for n = 8; 499,500 shifts for n = 1,000).
    • Best case — O(n): On an already sorted array, there are 0 inversions. The inner while loop fails immediately on each pass, doing n - 1 comparisons and 0 shifts.
    • Average case — Θ(n²): In a random permutation of distinct items, each of the n(n - 1) / 2 pairs has a 1/2 chance of being inverted, giving n(n - 1) / 4 expected shifts.

    That explains the bottleneck: moving elements one neighbor at a time can fix at most one inversion per step. To beat O(n²), an algorithm must move elements across long distances so each comparison helps resolve many inversions at once.

  3. Part 1: Beat O(n²) in the worst case with merge sort

    Divide and conquer means splitting an array into smaller subproblems of the same kind, solving them recursively, and combining their results. Merge sort cuts the array in half, recursively sorts the left half and the right half, and merges the two sorted halves using two front pointers i and j:

    def merge_sort(a):
        if len(a) <= 1:
            return list(a)
    
        mid = len(a) // 2
        left = merge_sort(a[:mid])
        right = merge_sort(a[mid:])
    
        # Merge two sorted halves by repeatedly taking the smaller front item
        merged = []
        i = 0
        j = 0
        while i < len(left) and j < len(right):
            # Using <= keeps equal items in their original left-to-right order
            if left[i] <= right[j]:
                merged.append(left[i])
                i += 1
            else:
                merged.append(right[j])
                j += 1
    
        merged.extend(left[i:])
        merged.extend(right[j:])
        return merged
    

    Why is merge sort O(n log n) in the worst case? When merging two sorted lists whose combined length is m, every comparison appends one element to merged, and as soon as one list runs out the rest of the other list is copied with zero comparisons — so merging m items takes at most m - 1 comparisons on every input. Expressing total work T(n) with a recurrence relation (an equation defining T(n) from smaller problem sizes):

    T(n) = 2 * T(n / 2) + c * n,    T(1) = c
    
    Level 0:  1 array     of size n       ->  c * n total merge work
    Level 1:  2 subarrays of size n / 2   ->  2 * c * (n / 2) = c * n work
    Level 2:  4 subarrays of size n / 4   ->  4 * c * (n / 4) = c * n work
      ...
    Level k:  n subarrays of size 1       ->  stops when n / 2^k = 1, so k = log2(n)
    
    Total work across all levels = c * n * log2(n) + c * n = O(n log n)
    

    Concrete numbers show the speedup: - For n = 8, merge sort uses at most 4 * 1 (size-2 merges) + 2 * 3 (size-4 merges) + 1 * 7 (size-8 merge) = 17 comparisons in the worst case, compared with 28 for insertion sort. - For n = 1,000,000, n log2(n) is about 2 × 10⁷ operations, whereas n² / 2 is 5 × 10¹¹ — roughly 25,000 times less work.

    Trade-offs: Merge sort is a stable sort (equal elements keep their original relative order), which comes at the cost of O(n) extra memory for merged. If you need worst-case O(n log n) time in place (O(1) extra memory), heapsort achieves it with a binary max-heap, though it is not stable and has poorer CPU cache locality.

  4. Part 1 alternative: Quicksort and expected O(n log n) time

    Quicksort goes the other way: it does the work before recursing so no merge buffer is needed. It chooses one element called the pivot and partitions the slice [lo..hi] in place so all elements <= pivot move left, all elements > pivot stay right, and the pivot lands at its final sorted index i:

    def quicksort(a, lo=0, hi=None):
        if hi is None:
            hi = len(a) - 1
        if lo >= hi:
            return
    
        # Lomuto partition using the last element as the pivot
        pivot = a[hi]
        i = lo
        for j in range(lo, hi):
            if a[j] <= pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
    
        # Place pivot between the <= pivot region and the > pivot region
        a[i], a[hi] = a[hi], a[i]
        quicksort(a, lo, i - 1)
        quicksort(a, i + 1, hi)
    

    If we choose the pivot uniformly at random from [lo..hi] (swap a random index into hi before partitioning), half the time the chosen pivot lands inside the middle 50% of sorted ranks — giving at worst a 1/4 vs. 3/4 split. Even a 3/4 upper bound shrinks subproblems exponentially ((3/4)^k * n = 1 after O(log n) good splits), while each recursion level still scans at most n elements total.

    More precisely, on any n distinct elements, randomized quicksort performs 2(n + 1)H(n) - 4n comparisons in expectation, where H(n) = 1 + 1/2 + ... + 1/n is the n-th harmonic number. Since H(n) ≈ ln(n), the leading term is 2n ln(n) ≈ 1.39 n log2(n) — for n = 1,000, the exact formula gives about 10,986 expected comparisons (versus 499,500 in quadratic time).

  5. Part 2: Quicksort's O(n²) worst case and how to prevent it

    Quicksort hits its worst case when every single partition is maximally unbalanced: a slice of m elements splits into 0 elements on one side and m - 1 elements on the other, removing only the pivot itself.

    With the deterministic last-element Lomuto partition above, three common inputs trigger this behavior: 1. Already sorted input [1, 2, 3, 4]: a[hi] is the maximum every time, putting m - 1 elements on the left and 0 on the right. 2. Reverse-sorted input [4, 3, 2, 1]: the first partition picks minimum 1 (0 left, m - 1 right) and swaps 4 to the end; the next picks maximum 4 (m - 1 left, 0 right), alternating min and max pivots all the way down. 3. All-equal input [5, 5, 5, 5]: because the condition a[j] <= pivot sends equal keys to the left side, every call puts m - 1 copies on the left and 0 on the right — even if the pivot is chosen at random.

    Sorted input [1, 2, 3, 4] with last-element pivot:
    
    Call 1 on [1, 2, 3, 4] (pivot 4): 3 comparisons -> [1, 2, 3] | 4 | []
    Call 2 on [1, 2, 3]    (pivot 3): 2 comparisons -> [1, 2]    | 3 | []
    Call 3 on [1, 2]       (pivot 2): 1 comparison  -> [1]       | 2 | []
    Call 4 on [1]                   : 0 comparisons (base case)
    
    T(n) = T(n - 1) + (n - 1)
         = (n - 1) + (n - 2) + ... + 1 + 0
         = n * (n - 1) / 2  =  Θ(n²) comparisons
    

    For n = 10 that is 45 comparisons; for n = 1,000 it jumps to 499,500 comparisons (45× slower than a random pivot's ~10,986), and the recursion tree becomes a chain of depth n - 1, risking a call-stack overflow (RecursionError in Python around n = 1,000).

    How to prevent it, and what each fix costs: - Random pivot: Gives O(n log n) expected time on distinct keys for one random integer per partition; worst case remains O(n²) in theory, and equal keys still need handling. - Median-of-three (median of a[lo], a[mid], a[hi]): Costs 2–3 extra comparisons per call and makes sorted/reversed inputs balanced, though crafted "median-of-three killer" arrays still force O(n²). - Three-way partition (Dutch National Flag) or Hoare partition: Three-way partitioning splits into < pivot, == pivot, and > pivot so an all-equal array finishes in one O(n) pass (slightly more swaps per step); Hoare's two-pointer partition stops on equal keys and swaps them, splitting all-equal arrays 50/50 in O(n log n). - Introsort (introspective sort): Starts with quicksort, tracks recursion depth, and switches to heapsort if depth exceeds 2 * floor(log2(n)). Used by C++ std::sort, it guarantees worst-case O(n log n) time with almost zero overhead on normal inputs. - Median-of-medians pivot: Finds a guaranteed central pivot deterministically in O(n) time, achieving deterministic worst-case O(n log n) but with a constant factor too large for everyday sorting.

  6. Part 3a: Count non-empty subsequences and permutations

    Count each structure by breaking it into one simple choice per position:

    1. Non-empty subsequences = 2^n - 1. A subsequence chooses any set of index positions and keeps those elements in their original left-to-right order (indices do not need to be adjacent). Walk across the n indices 0, 1, ..., n - 1: each index independently has 2 choices — keep or skip. Multiplying 2 choices across n independent positions gives 2 * 2 * ... * 2 = 2^n total subsequences. Exactly 1 of those skips every index (the empty subsequence []), leaving 2^n - 1 non-empty ones:

    Array [a, b, c] (n = 3):
      Keep 1 item : [a], [b], [c]
      Keep 2 items: [a, b], [a, c], [b, c]
      Keep 3 items: [a, b, c]
      Total = 3 + 3 + 1 = 7 = 2^3 - 1    (for n = 20: 2^20 - 1 = 1,048,575)
    

    2. Permutations = n!. A permutation rearranges all n index positions into a full ordering of length n. Slot 0 can pick any of the n positions; slot 1 can pick any of the remaining n - 1; slot 2 has n - 2 left, down to 1 choice for the last slot:

    permutations = n * (n - 1) * (n - 2) * ... * 2 * 1 = n!
    
    Array [a, b, c] (n = 3):
      [a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]
      Total = 6 = 3!                     (for n = 10: 10! = 3,628,800)
    

    (Note: if values repeat and you count distinct value sequences instead of distinct index arrangements, divide n! by c! for each value appearing c times — e.g., [1, 1, 2] has 3! = 6 index permutations, which collapse to 3! / 2! = 3 distinct value sequences.)

  7. Part 3b: Construct a super-quadratic sort via permutations

    Why did we need the permutation count rather than the subsequence count to build a sort? Every subsequence keeps elements in their original order, so the only subsequence of length n is the unsorted input itself — scanning 2^n - 1 subsequences never reorders anything. By contrast, the n! permutations contain every possible reordering of the n elements, so at least one of them is guaranteed to be sorted.

    That gives permutation sort: 1. Generate the n! permutations of the input's positions one by one in a fixed order (such as lexicographic order of indices). 2. Test each candidate with is_sorted (up to n - 1 adjacent comparisons). 3. Return the first candidate that passes is_sorted.

    from itertools import permutations
    
    
    def is_sorted(seq):
        for i in range(len(seq) - 1):
            if seq[i] > seq[i + 1]:
                return False
        return True
    
    
    def permutation_sort(a):
        # Check up to n! candidate orderings of the input positions
        for candidate in permutations(a):
            if is_sorted(candidate):
                return list(candidate)
        return []
    
    • Guaranteed termination and correctness: permutations(a) yields a finite list of n! rearrangements, and every comparable array has at least one non-decreasing rearrangement among them (even [], which yields one empty tuple () that passes is_sorted).
    • Running time: itertools.permutations generates candidates in lexicographic order of input indices (0, 1, ..., n - 1) down to (n - 1, ..., 1, 0).
      • Best case — O(n): If a is already sorted, the very first tuple passes is_sorted.
      • Worst case — Θ(n · n!): On a strictly reversed array of distinct elements, the sorted order (n - 1, ..., 1, 0) is the very last of the n! candidates. Materializing and checking each length-n tuple costs Θ(n), for Θ(n · n!) total work (Θ(n!) if permutations are stepped in place with amortized O(1) updates and early-exit checks).
      • Average case — Θ(n · n!): On a random permutation of distinct values, the sorted tuple is equally likely to be at any of the n! positions, checking (n! + 1) / 2 candidates on average.

    Compare how fast 2^n - 1 and n! blow past n² (already n! > n² for all n >= 4):

       n            n²         2^n - 1                        n!
       4            16              15                        24
      10           100           1,023                 3,628,800
      20           400       1,048,575   2,432,902,008,176,640,000 (~2.4 × 10¹⁸)
    

    (Bonus: if the interviewer asks for a polynomial sort slower than O(n²), stooge sort swaps the endpoints if out of order, then recursively sorts the first 2/3, the last 2/3, and the first 2/3 again: T(n) = 3 * T(2n / 3) + O(1) = Θ(n^(log(3)/log(1.5))) ≈ Θ(n^2.71) worst-case and best-case time.)

Intuition & how it works

Think of sorting books on a long library shelf. Insertion sort slides each misplaced book past its neighbors one slot at a time (O(n²)). Merge sort and quicksort work like tournament brackets or mailroom sorting bins: by repeatedly cutting the pile in half, elements leap across large stretches of the array in a single pass so every book participates in only O(log n) rounds (O(n log n)). At the opposite extreme, permutation sort ignores comparison clues while building candidates and simply tries arrangements of the shelf one after another until one happens to be in alphabetical order (Θ(n · n!)).

Fixing order one adjacent pair at a time is slow because a reversed array of n items has n(n - 1) / 2 out-of-order pairs, and each adjacent shift fixes only one pair. Quicksort avoids that quadratic trap only when its chosen pivot (dividing element) splits the array into two roughly comparable pieces; if a naive rule like "always pick the last item" runs on an already sorted array, every split leaves 0 items on one side and n - 1 on the other, collapsing right back to O(n²).

Walk through n = 4 items [4, 2, 3, 1]: - Insertion sort fixes out-of-order pairs one neighbor at a time ([2, 4, 3, 1] -> [2, 3, 4, 1] -> [1, 2, 3, 4]), doing 1 + 1 + 3 = 5 shifts (up to 4 * 3 / 2 = 6 in the worst case). - Merge sort splits into [4, 2] and [3, 1], sorts them into [2, 4] and [1, 3] (1 comparison each), and merges their fronts into [1, 2, 3, 4] (3 comparisons) — 5 comparisons across log2(4) = 2 levels. - Quicksort (last-element pivot) picks pivot 1 on [4, 2, 3, 1] and gets an unbalanced 0 vs. 3 split ([], 1, [2, 3, 4]), then 0 vs. 2 on [2, 3, 4] (pivot 4), showing how extreme pivots waste passes. - Permutation sort enumerates up to 4! = 24 arrangements of the 4 items ([4, 2, 3, 1], [4, 2, 1, 3], ..., [1, 2, 3, 4]) and stops at the sorted one, reaching all 24 candidates when [4, 3, 2, 1] is strictly reversed.

Key points

  • Insertion sort removes one inversion per shift: An inversion is an out-of-order pair i < j with a[i] > a[j]. That gives n(n - 1) / 2 shifts in the worst case (Θ(n²)), n(n - 1) / 4 on average (Θ(n²)), and 0 shifts with n - 1 comparisons (O(n)) when already sorted.
  • Merge sort guarantees O(n log n) worst-case time: Its recurrence relation (equation relating work at size n to smaller sizes) T(n) = 2T(n / 2) + c·n has log2(n) levels doing O(n) merge work each, trading O(n) extra memory for stability and predictable speed; heapsort achieves worst-case O(n log n) in O(1) extra space.
  • Quicksort runs in O(n log n) expected time when pivots are balanced: Choosing a random pivot on distinct keys averages 2(n + 1)H(n) - 4n ≈ 1.39 n log2(n) comparisons (~10,986 for n = 1,000), working in place without a merge buffer.
  • Quicksort's worst case is Θ(n²) from 0 vs. m - 1 splits: Last-element Lomuto partitioning on sorted, reverse-sorted, or all-equal arrays triggers T(n) = T(n - 1) + (n - 1) = n(n - 1) / 2 comparisons (499,500 for n = 1,000) and O(n) recursion depth.
  • Combinatorial counts: Choosing keep or skip independently at each of n indices yields 2^n - 1 non-empty subsequences (subsets keeping original order); filling n slots one by one yields n! permutations (full reorderings).
  • Permutation sort is Θ(n · n!) in the worst case: Checking each of the n! position orderings with O(n) tuple construction and is_sorted always terminates and already exceeds n² for every n >= 4 (10! = 3,628,800 vs. 10² = 100).

Common mistakes

  • Omitting which case a bound describes: Saying "quicksort is O(n log n)" without qualification is incomplete — plain quicksort is O(n log n) on average (or in expectation with random pivots) and O(n²) in the worst case.
  • Claiming a random pivot gives worst-case O(n log n): Randomization makes the expected time O(n log n) on every distinct-key input, because bad luck can still pick extreme pivots repeatedly.
  • Overlooking duplicate keys in quicksort: A two-way Lomuto partition using <= sends all copies of the pivot to the left side, degrading an all-equal array [5, 5, ..., 5] to Θ(n²) even with a random pivot unless you use three-way or Hoare partitioning.
  • Saying 2^n non-empty subsequences or confusing subsequences with subarrays: Forgetting to subtract the 1 empty subset gives 2^n instead of 2^n - 1, and counting contiguous subarrays gives n(n + 1) / 2 instead of 2^n - 1.
  • Trying to sort by enumerating subsequences: Subsequences preserve original left-to-right order, so none of the 2^n - 1 subsequences ever reorders elements; you need the n! permutations.
  • Forgetting the O(n) cost per permutation: Materializing and testing each candidate tuple with itertools.permutations takes Θ(n · n!) time in the worst case, not O(n!), unless stepping and early-exit checking are done in place in amortized O(1) time (constant average work per step across the whole sequence).

Follow-up questions

  • How does the count of n-element permutations prove the Omega(n log n) worst-case comparison lower bound? Model any comparison sort as a decision tree — a binary tree where each internal node asks one a <= b question, branches left or right on the answer, and reaches a leaf that specifies one final index rearrangement. Because all n! input permutations of distinct keys require n! different inverse rearrangements to come out sorted, the tree must have at least n! leaves. A binary tree of height h (worst-case number of comparisons) has at most 2^h leaves, so 2^h >= n!, meaning h >= log2(n!); since the largest n / 2 factors of n! are each at least n / 2, log2(n!) >= (n / 2) log2(n / 2) = Ω(n log n) (for n = 8, ceil(log2(40,320)) = 16 minimum comparisons vs. merge sort's 17).
  • What practical pivot choices or hybrid fallbacks prevent quicksort from degrading to quadratic time, and what overhead does each introduce? A random pivot gives O(n log n) expected time on distinct keys at the cost of one random number per partition, though no deterministic worst-case bound. Median-of-three (first, middle, last) costs 2–3 comparisons per partition and fixes sorted/reversed inputs, but adversarial inputs can still force O(n²). Introsort runs quicksort and falls back to heapsort only if recursion depth exceeds 2 log2(n), guaranteeing true worst-case O(n log n) time with negligible overhead, while three-way partitioning (<, ==, >) or Hoare partitioning keeps duplicate-heavy arrays at O(n) to O(n log n) (whereas deterministic median-of-medians guarantees O(n log n) but has too high a constant factor for practical sorting).
  • If an algorithm repeatedly shuffles the array at random until it becomes sorted, what is its expected runtime, and how do its guarantees differ from deterministic permutation enumeration? This randomized algorithm (bogosort) hits the single sorted order of n distinct elements with probability 1 / n! on each uniform Θ(n) shuffle. The trial count follows a geometric distribution (waiting time for a coin with success probability p, which has mean 1 / p), giving n! expected shuffles and Θ(n · n!) expected time — the same asymptotic order as enumeration, except bogosort can repeat failed arrangements. As a result, bogosort has no worst-case upper bound (after t shuffles, the chance of still being unsorted is (1 - 1 / n!)^t > 0, terminating with probability 1 rather than deterministic certainty), whereas fixed enumeration never repeats a candidate, caps the worst case at n! candidates, and averages (n! + 1) / 2 candidates on a random input (half as many tries).
  • In what practical scenarios is quadratic insertion sort still preferable to an O(n log n) sorting algorithm? First, on tiny subarrays (n <= 16 to 64), insertion sort's tight loop, sequential memory access, and zero allocation beat recursive sorts — which is why CPython's Timsort and C++ std::sort use insertion sort as their base case. Second, on nearly sorted data, insertion sort runs in O(n + I) time for I inversions: if every element starts at most k slots from its final sorted spot, I <= n * k, giving O(n * k) time (O(n) when k is a small constant). Third, it works online (maintaining a sorted list as items arrive one by one) and sorts stably in place with O(1) extra memory.

Follow-up questions

Similar questions

More Mercor interview questions

All 44 Mercor questions →