Sorting: Practice Questions
100 questions. Try each one yourself before checking the answer.
Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.
Bubble sort compares neighbours and swaps them when they are out of order, pass after pass. After pass k, the k largest items are in their final places at the right end, so each pass can stop one position earlier.
Write bubble_sort(a, stats) that sorts a in place and returns None (like list.sort). It records comparisons and swaps in the stats dict and prints the list after every pass when stats["trace"] is true. Trace [5, 1, 4, 2, 8, 3]. Then show that every swap removes exactly one inversion (a pair i < j with a[i] > a[j]), so swaps must equal the inversion count from an O(n^2) pair count. Check that on 500 seeded lists.
A pass that makes no swaps proves the list is sorted, so the sort can stop. A sharper version also ends the next pass at the position of the last swap, because everything after it is already final.
Write three in-place bubble sorts (each returns None): plain, early_exit and last_swap. Count comparisons and passes for n = 1,000 on sorted, reversed, random, and "one swap away" input (a sorted list with two neighbours in the middle swapped). Then show the turtle: a sorted list whose smallest item sits at the end. Compare it with a "rabbit" (the largest item at the front).
Selection sort finds the minimum of the unsorted part and swaps it to the front. Write selection_sort(a, stats) in place (returns None) that counts comparisons and swaps. Print both on sorted, reversed and random input at n = 1,000.
Selection sort always makes n(n - 1)/2 comparisons, whatever the input (it is not adaptive), but at most n - 1 swaps. Then compare it with bubble sort's swaps on the same inputs, and compute the total cost under a made-up model where one write costs 50 times as much as one comparison (think of flash memory).
Insertion sort works like sorting a hand of cards: take the next item and shift larger items one place right until the item's slot appears. The invariant is that a[:i] is sorted before step i.
Write insertion_sort(a, stats, key=None) in place (returns None; key works as in sorted) that counts comparisons and shifts. Print one line per insertion for [7, 3, 5, 1, 6, 2]. Then check on 500 seeded lists that shifts equals the inversion count exactly and that comparisons <= shifts + n - 1. State best, average and worst time, and show the sort is stable by comparing it with sorted(key=...) on the same fuzz.
Insertion sort's cost is O(n + inversions), so it is adaptive: the closer the input is to sorted, the less it does. Selection sort is not. At n = 2,000 time both on random, sorted, reversed and nearly sorted input (a sorted list with 20 seeded adjacent swaps). Sort a fresh copy inside the timed function each run, and use best_of(fn, repeats=3).
Print comparisons, shifts and time, and the ratio of random to nearly sorted time for insertion sort. Say why library sorts hand small or nearly sorted parts to insertion sort.
Put bubble sort (with the last-swap early exit), selection sort and insertion sort in one table. For random lists at n = 500, 1,000, 2,000, print comparisons, writes (list slots assigned: a swap writes 2, a shift writes 1, and the final placement of a moved item writes 1) and the best_of(fn, repeats=3) time, each sort on a fresh copy.
Then print what happens to each column when n doubles, and read the conclusions from those printed ratios.
A loop invariant is a statement that is true after every outer iteration, and it explains why the sort is correct. Write bubble, selection and insertion sort so each takes after_step(a, k), a callback called after k outer iterations have completed. Assert these invariants (with truth = sorted(original)):
- bubble: the last
kitems equaltruth's lastk(the tail is final); - selection: the first
kitems equaltruth's firstk; - insertion:
a[:k+1]is sorted, is a permutation oforiginal[:k+1], anda[k+1:]is untouched.
Fuzz all three on 1,000 seeded lists that include empty, one item, all equal, duplicates, negatives, sorted and reversed. Correct means ordered and a permutation of the input (Counter equality). Exceptions count as failures. Finally run an insertion sort whose loop starts at index 2 and show the invariant catching it.
A sort is stable if items that compare equal keep their input order. Take records (grade, name) sorted by grade only. DSA Topic 2 showed that sorted() is stable; here you find out which hand-written sorts are.
Write bubble, insertion and selection sort on records by grade, in place. Run them on [(2, 'a'), (2, 'b'), (1, 'c')] and print each result next to sorted(records, key=...). Then fuzz 500 seeded record lists and count how many results differ from the stable sorted(key=...) answer. Add a broken insertion sort that uses >= instead of > and count its failures too. Explain from the counts why each sort is or is not stable.
Selection sort is not stable, but you can fix it two ways.
- Decorate: pair each record with its input index and sort by
(key, index). No two pairs tie, so any sort gives a stable result. Writeselection_sort_stable(records, key)that returns a new list and costsO(n)extra space. - Shift instead of swap: find the first minimum, then slide the items between it and the front one place right and put the minimum in front. Write
selection_sort_shift(a, key, stats)in place, countingwrites.
Fuzz both against sorted(key=...) on 500 seeded lists with many ties, count how often the plain swap version fails, and compare the writes of the swap and shift versions on reversed and random input at n = 300.
To sort by a major key and break ties by a minor key, sort by the minor key first, then by the major key with a stable sort. DSA Topic 2 did this with sorted(). Here the passes use hand-written sorts.
Records are (dept, name). The target is sorted(key=lambda r: (r[0], r[1])). On 12 seeded records print three attempts beside the target: (a) name pass then dept pass, both with insertion sort; (b) the same but the dept pass uses selection sort; (c) insertion sort in the wrong order (dept first, then name). Then run all three on 300 seeded lists and count the correct ones. This idea, applied digit by digit, is LSD radix sort, met later in this topic.
sorted(a, key=f, reverse=True) has a precise meaning: f is called once per item, and reverse=True compares the other way, so equal items keep their input order. It does not sort and then flip the output.
Write insertion_sort(a, key=None, reverse=False) that returns a new list (like sorted) and leaves a alone. Decorate each item as (key(x), x) first, sort on the keys only, then undecorate. Count the key calls (it must be n), and compare with a naive version that calls key inside every comparison. Show on a tie that reversing the output gives a different, wrong order. Fuzz against sorted(a, key=..., reverse=...) on records with ties, counting exceptions as failures.
Insertion sort moves an item one place at a time. Shell sort runs insertion sort over items gap apart, for a shrinking list of gaps ending in 1. Far moves happen early, and the final gap-1 pass sees a nearly sorted list. Use Knuth's gaps ..., 40, 13, 4, 1 (h = 3h + 1, every h < n).
Write shell_sort(a, stats, gaps=None): in place, returns None, counting comparisons and shifts. Insertion sort is the same function with gaps=[1]. Fuzz it. Count comparisons against insertion sort for n = 500..4,000, then Shell sort alone from n = 1,000 to 64,000, and print the exponent log2(c(2n) / c(n)) for each doubling. Show that Shell sort is not stable by searching small inputs for the first failure.
Insertion sort's slot for the next item lies in a sorted prefix, so bisect.bisect_right (DSA Topic 3) can find it with a binary search. That drops the comparisons to O(n log n), but the items still have to move: the moves stay O(n^2).
Write binary_insertion_sort(a) in place (returns None). Count comparisons with a small wrapper class whose __lt__ adds to a counter, for plain insertion sort and the binary version at n = 500..4,000. Print the shifts too. Time both on bare ints (a fresh copy inside each timed call). Then show bisect_right keeps the sort stable and bisect_left does not.
Split the list in half, sort each half recursively, and merge the two sorted halves. The merge is the two-pointer merge of two sorted lists from DSA Topic 2, the combine step of DSA Topic 8, taking from the left on ties. Use half-open ranges [lo, hi).
Write merge_sort(a, stats, key=None) that returns a new list and leaves a alone, counting comparisons and writes and the deepest recursion level. Trace 8 items with a depth-indented print. Show T(n) = 2T(n/2) + n = O(n log n) by counting comparisons against n log2 n for n = 2^4 .. 2^16. Show that the depth is about log2(n) (so 10^6 items need about 20 frames), and check stability and correctness with a fuzz.
The slicing merge sort builds new lists at every level. A smarter version allocates one buffer once, merges a[lo:mid] and a[mid:hi] into it by index, and copies back. Write both: merge_sort_slices(a) returns a new list, and merge_sort_buffer(a) sorts in place and returns None.
Measure tracemalloc peaks (as bytes per item) and best_of times for both at n = 10^4 and 4 * 10^4, timing on a fresh copy inside the timed function. Check both against sorted(). Say what the numbers show: both need O(n) extra space, so merge sort is not in place. In-place merging exists and is complicated; it is named only.
Merge sort needs no recursion. Merge runs of width 1 into runs of 2, then 2 into 4, then 4 into 8, and so on: ceil(log2 n) passes, each O(n). Use half-open ranges and two lists that swap roles each pass.
Write bottom_up(a, stats) (returns a new list), and a top-down top_down(a, stats) for comparison. Fuzz both for order, permutation and stability. Show that the comparison counts match when n is a power of 2, and print what happens for other n. Then natural_merge(a, stats) starts from the runs the input already contains instead of width 1; print its comparisons and starting runs on five input shapes.
DSA Topic 2 split an array into two groups in place. Lomuto partitioning does the same around a value taken from the array: the pivot is the last item, and one scan keeps a[lo:i] smaller than the pivot and a[i:j] at least the pivot. At the end the pivot is swapped to index i, which is its final sorted position.
Write lomuto_partition(a, lo, hi, stats) with a closed range [lo, hi] that returns the pivot's index, counting comparisons and swaps (exchanges of two different positions). Trace [7, 2, 9, 4, 1, 8, 3, 5] with i and j after each step. Check that the pivot's index equals lo plus the number of smaller items, and fuzz sub-ranges: items outside the range must not move.
After a partition the pivot is in its final place, so sort the two sides recursively and there is nothing to merge. Use the Lomuto partition with a closed range [lo, hi] and the last item as pivot.
Write quick_sort(a, stats): in place, returns None, counting comparisons and the deepest recursion level. Plain recursion, so keep n <= 800. Compare comparisons on random input with the exact expectation 2(n + 1)H(n) - 4n (H is the harmonic number) and with 1.39 n log2 n, and on sorted input with n(n - 1)/2. Print the deepest levels. Show that quicksort is not stable, and fuzz it against sorted(). State best, average and worst case and which one matters in practice.
With the last item as pivot, sorted input makes every split n - 1 and 0. Show it: the comparisons are exactly n(n - 1)/2 on sorted input, on reversed input, and (with <) on all-equal input. Print a table against random input for n = 200, 400, 800, with the comparisons, the time (a fresh copy inside the timed call) and the ratio between them.
Then raise n to 2,000 on sorted input and catch the RecursionError, printing only its type name. The cures (random pivots, recursing on the smaller side) come later in this topic.
Records with small integer keys 0..k can be sorted with no comparisons at all. Count each key, turn the counts into start positions with a prefix sum (DSA Topic 6), then walk the records left to right and place each one at its key's next free slot. Equal keys keep their input order, so the sort is stable. DSA Topic 2 counted values and rewrote them, which works for bare numbers but cannot carry records.
Write counting_sort(records, key, k, stats) returning a new list and counting placements. Trace 8 records. Show two broken versions on the same input: rewriting from the counts (labels lost) and walking right to left with start positions (order inside a key reversed). Then sort 100,000 records with keys 0..100: check against sorted(key=...), print O(n + k) and both times, with no time verdict. State the time and space.
Counting sort needs one counter per possible key, so its cost is O(n + k), where k is the largest key. Write counting_sort_ints(a, k) for bare ints in 0..k, returning a new list.
Compute (never allocate) the memory a count array would need for keys up to 10^9. Then, for n = 10,000 items and k = 10, 1,000, 30,000 and 1,000,000, print the work n + k, the number of comparisons sorted() makes (count them with a small wrapper class whose __lt__ adds to a counter), and both times. Decide the winner from the counted work, print the break-even k as a computed number, and print how much counting sort's time grew beside how much its work grew.
sorted(iterable) accepts any iterable and returns a new list. list.sort() works in place and returns None. Show both with a # STEP label for each fact, and print the evidence:
a = a.sort()leavesNoneina.sorted()takes a string, a tuple, a dict (its keys), a set and a generator.- Both are stable: assert that every group of equal keys keeps its input label order for
sorted()and forlist.sort()on a copy. One assert each forkey=being called once per item, and forreverse=Truekeeping equal items in input order. - Count comparisons with a wrapper class whose
__lt__adds to a counter:n - 1on sorted input, close ton log2 non random input. - Time hand-written
merge_sort(a)(returns a new list) andquick_sort(a)(in place, Lomuto, closed range[lo, hi], last-item pivot) againstsorted()on 100,000 random ints, and print the ratios. Then show what a Python-level__lt__costs by sorting the same numbers wrapped in the counting class, and print the time for ints with one float appended (a generic C comparison) with no verdict.
A tuple key compares field by field. Sort employees by department ascending, salary descending, then name ascending with key=lambda e: (e.dept, -e.salary, e.name). Negation works for numbers only: a descending text field needs two stable passes (or a comparator, later in this topic). Also show operator.itemgetter with several fields on dict records.
Do not trust the output by eye. Write follows(a, b), the rule as an explicit if chain, and test every adjacent pair of the result on 500 seeded lists with plenty of ties. Include three versions: the tuple key, two stable passes for dept ascending and name descending, and the wrong reverse=True on the whole tuple. Show that negating a string raises TypeError (print its type name).
sorted() only ever asks a < b. Show what that means for your own classes:
- A class without
__lt__makessorted()raiseTypeError(print the type name, not the message). - A class with a hand-written
__lt__and__eq__sorts. key=attrgetter('dept', 'age')needs no method at all.@dataclass(order=True)compares fields in declaration order.- A list mixing an
intand astrraisesTypeError, and so does aNonein a field. Fix theNonecase with a key that puts missing ages last.
Check every result against sorted(key=lambda ...) on seeded people.
Route ten situations to a method. Write choose(s) taking a dict of properties (n, library, writes_costly, bigger_than_memory, stable_needed, int_range, descents, the count of places where a[i] > a[i+1]) and returning (method, deciding property). The methods are insertion sort, selection sort, merge sort, quicksort, counting sort and sorted().
Assert each answer against the one you expect, then back the ones that can be backed by a count with a measured number from the run: shifts against comparisons, swaps against shifts, a stability check, n + k against n log2 n, and the number of merge passes for data bigger than memory. Print one row per situation.
Hoare's partition starts two indices at the ends and moves them inward, swapping each pair that sits on the wrong side. It uses a closed range [lo, hi] and the middle item a[(lo + hi) // 2] as the pivot.
Write hoare_partition(a, lo, hi, stats). It works in place and returns j with a[lo..j] <= pivot <= a[j+1..hi]. The pivot need not end up at j. Trace it on 8 items, then fuzz the invariant. Write lomuto_partition(a, lo, hi, stats) (last-item pivot) beside it. Count comparisons and swaps for one partition of 10,000 items of each shape (random, sorted, all equal), and print the split sizes. Print which partition swaps less from the printed numbers.
With Hoare's partition the pivot may end anywhere, so recurse on [lo, j] and [j + 1, hi], not j - 1. Write quick_sort(a, stats, bug=False): in place, returns None, closed ranges, middle pivot, counting comparisons and the deepest level. bug=True recurses on [lo, j - 1] and [j + 1, hi] as Lomuto code would. Fuzz both against sorted() (include empty, all-equal and two-value lists, and count any exception as a failure), and print the first small input the buggy version gets wrong.
Then write quick_sort_lomuto(a, stats) and compare comparisons on random, sorted and few-unique input (values 0..9) at n = 800, where plain recursion fits. Run the Hoare sort alone at n = 10,000 on five shapes.
Write quick_sort(a, rule, rng) for Lomuto quicksort on a closed range [lo, hi]: in place, returns the number of comparisons. The pivot rule is "first", "last", "middle", "median3" (the median of the first, middle and last items, counted as 3 comparisons) or "random". The chosen pivot is swapped to a[hi], then partitioned.
Print one table of comparisons at n = 800 (plain recursion fits) for random, sorted, reversed, organ pipe (up then down) and few-unique (0..9) input. For each rule, read from the table which shape hurts it most, and print that shape and the ratio of its count to the rule's random-input count. Print the sorted-input row beside n(n - 1)/2, and what the organ pipe does to median of three as a ratio, without assuming it.
Pick the pivot at random and no fixed input is bad any more: the expected comparisons are 2(n + 1)H(n) - 4n (H is the harmonic number, about 1.39 n log2 n for large n) on every input of distinct keys. Repeated keys are different: show one all-equal row and name the fix.
Write quick_sort(a, rng, stats): in place, returns None, closed range [lo, hi], with its own Lomuto partition after swapping a random pivot to a[hi]. Count comparisons and the deepest level. For n = 1,000 and 10,000, on sorted and random input, run 20 seeded generators and print the mean and the worst comparison count beside the formula. Print the probability of the quadratic case as a base-10 logarithm. Fuzz against sorted() including the empty list. State best, average and worst case, and which matters in practice.
DSA Topic 2's Dutch national flag, taken around a pivot value, splits a range into < pivot, == pivot and > pivot in one pass with three indices. Write partition3(a, lo, hi, pivot, stats) on a closed range [lo, hi], returning (lt, gt) so that a[lo:lt] < pivot, a[lt:gt+1] == pivot and a[gt+1:hi+1] > pivot. Count each < or > test as one comparison and trace it on 9 items.
Write quick_sort3(a, rng, stats) (in place, returns None, random pivot value) that recurses only on the outer parts. Compare it with a Lomuto quicksort on all-equal input at n = 800, then with a Hoare quicksort (middle pivot) on values 0..9 at n = 100,000, counting comparisons and timing both. Also run random distinct input at n = 10,000. Fuzz against sorted(). Decide each winner from the counts, not the clock.
Quicksort with a last-item pivot on sorted input splits every part into n - 1 items and 0 items, so plain recursion goes n frames deep. Fix the depth without fixing the time: recurse into the smaller part and loop on the larger one. Each recursive call then gets at most half the items, so the depth is at most log2(n) even when the running time is O(n^2).
Write quick_sort_plain(a, stats), quick_sort_smaller(a, stats) (recurse on the smaller side, loop on the larger) and quick_sort_stack(a, stats) (no recursion: a list used as a stack, as DSA Topic 8 did, pushing the larger part first so the smaller part is popped next). All three sort in place and return None, with a Lomuto partition on a closed range [lo, hi]. Run them on sorted input of n = 3,000: catch the RecursionError from the plain one and print only its type name. Also show the student bug that gets the sides the wrong way round (recurse on the larger part, loop on the smaller one) failing on that same input while passing on random input. Print the deepest level and the largest stack against log2(n), and fuzz the working versions against sorted().
Recursion is expensive on tiny parts: a call, a partition and a merge to order three items. A hybrid stops recursing when a part has at most cutoff items and insertion sorts it instead (insertion sort is fast on short parts, as the elementary sorts showed). Library sorts, Timsort included, use this idea.
Write quick_sort(a, cutoff, stats) (Lomuto, closed range [lo, hi], recurse on the smaller side) and merge_sort(a, cutoff, stats) (top-down, half-open range [lo, hi), one buffer), both in place, returning None, plus an insertion helper. Cutoff 1 means no hybrid at all. At n = 20,000 random ints, run cutoffs 1, 8, 16, 32 and 64, and print comparisons, recursive calls (or partitions) and best_of time for each, with every time as a ratio to the fastest row of its own sort. Fuzz every cutoff against sorted(), and check that the merge version stays stable.
To find the k-th smallest item you do not need the whole list in order. Partition around a pivot: if the pivot lands at index k you are done, otherwise the answer is in just one side, so continue into that side with a loop (never recursion). With a random pivot and distinct keys the work is T(n) = T(n/2) + n = O(n) on average, and O(n^2) in the worst case; heavy duplicates are a second bad case.
Write quickselect(a, k, rng, stats): Lomuto partition on a closed range [lo, hi], k is a 0-based index, rng is a random.Random (or None for the last item as pivot). It reorders the list it is given and returns the item, so callers pass a copy; it raises IndexError for k outside 0..n-1, negative k included (unlike sorted(a)[k], which counts from the end). Fuzz it against sorted(a)[k] for every k from 0 up, on small inputs (empty lists included), and check k = -1 raises. Count comparisons at n = 100,000 for k = 0 and the median against a hand-written merge sort's comparisons, show the last-item pivot on sorted input reaching n(n - 1)/2, and print the times beside the counts.
The median is just the n // 2-th smallest item, so quickselect finds it without sorting. For odd n that item is the median. For even n it is the upper median, and the lower median is the largest item to its left (after a selection, every item left of index k is <= the one at k, so one scan finds it). The median of an even-length list is the mean of the two.
Write select(a, k, rng, stats) (reorders a, returns the k-th smallest; loop, Lomuto, closed range) and median(values, rng, stats) returning a new value without touching values. Check it against statistics.median on seeded odd and even lists, the empty list included. Then at n = 1,000,000 print comparisons for quickselect and the comparison lower bound for sorting beside the two times, and say what each number shows. Name median of medians without building it.
You want the k smallest of n = 40,000 records (score, id), in order. Four ways: (1) sorted(a)[:k], O(n log n); (2) k selection passes, each scanning for the smallest remaining item, O(nk), run only for k = 10; (3) quickselect for the k-th, then sort those k, O(n + k log k); (4) partial quicksort, a random-pivot quicksort that recurses only into parts that overlap the first k positions.
Write top_sorted, top_passes, top_select and top_partial (each returns a new list). Many scores tie, so the explicit key is the whole tuple (score, id): the ids are unique, and the answer becomes unique too, so all four can be compared directly. Count comparisons for k = 10 and k = 1,000 with a wrapper class whose __lt__ adds to a counter, time the same functions on plain tuples, and print both. Name the heap version (DSA Topic 15) with its bound; use no heap here.
LSD radix sort (least significant digit first) sorts non-negative integers without comparing two of them (beyond one max() scan): sort by the last digit, then by the next digit, and so on. After pass d the numbers are in order by their last d digits. This only works if every pass is stable, because an equal digit must keep the order the earlier passes made (it is the two-stable-pass sort of two keys, once per digit).
Write radix_sort(a, base, stats, trace=False), which returns a new list and uses a stable counting pass per digit: count the digit, turn the counts into start positions with a prefix sum (DSA Topic 6), and place items walking left to right. Trace base 10 on [170, 45, 75, 90, 802, 24, 2, 66], one line per pass. Show the student bug that walks right to left. Then for 10^5 random 32-bit ints print passes, placements and count-array work for bases 16, 256 and 65,536, check against sorted(), and print the times without a time verdict.
LSD radix sort has two gaps. Negative ints: (x // div) % base quietly gives a non-negative digit for a negative x in Python, and the pass count comes from max, so a naive call returns a wrong order with no error. Fix it two ways: offset every key by the minimum, or split the negatives (sort their magnitudes and reverse) from the rest and join.
Strings: sort characters from the right with ord. For fixed-length codes such as 'AB12' that is one pass per position. For variable lengths, pad shorter strings on the right with a code that sorts before every character, so 'ab' comes before 'ab0'. (Most-significant-digit radix sort handles variable lengths without padding; it is named, not built.)
Write radix_sort(a, base), radix_signed_offset(a), radix_signed_split(a) and radix_strings(words), each returning a new list. Show the naive call on negatives, then the student bug that pads strings with '0', finding its smallest failing input from a seeded fuzz. Fuzz everything against sorted(), empty input and empty strings included.
Bucket sort suits numbers spread evenly over a known range. For n floats in [0, 1): put x into bucket int(x * n), insertion sort each bucket, and concatenate. If the data is uniform, a bucket holds about one item, so the expected cost is O(n). If the data is clustered, most items share a few buckets and each bucket's insertion sort is quadratic.
Write bucket_sort(a, stats), which returns a new list and records shifts (insertion sort's moves) and the bucket sizes. Print the histogram of bucket sizes for n = 100,000 uniform floats beside what a Poisson(1) count predicts (n e^-1 / k! buckets of size k), and the sum of squared sizes against n. Then run the clustered cases: n = 20,000 in [0, 0.01), and all items in one bucket for n = 500, 1,000, 2,000 (shifts should grow about 4x per doubling). Check against sorted() including empty input, and print the time beside sorted() with no verdict on the clock.
A list contains only 0, 1 and 2. Three ways to sort it: count and rewrite (count each value, then write them back: two passes), the Dutch national flag (one pass with three regions, DSA Topic 2), and sorted(). They agree on bare numbers, but they differ on records keyed 0, 1 and 2: the Dutch flag swaps items over long distances, so equal keys come out in a scrambled order. A stable counting sort (count, prefix sum, place left to right) keeps the order and returns a new list.
Write count_and_rewrite(a) and dutch_flag(a, key) (both in place, returning None) and counting_records(a, key) (a new list). Print the three agreeing on bare numbers (a fuzz that includes the empty list), then records where the Dutch flag scrambles each group and the stable sort does not, with a fuzz counting how many record lists each one gets out of order. Print the reads/writes, swaps and comparisons, and the times without a verdict.
Python's sorted() is Timsort, and it is much faster than the O(n log n) bound on the data people really have. Measure it: wrap items in a class whose __lt__ adds to a counter (the sort only ever calls <), and count the comparisons at n = 10,000 for sorted, reversed, random, organ pipe, nearly sorted (20 adjacent swaps), few unique, all equal, two sorted halves swapped, two interleaved runs, and a sawtooth of period 100. Beside each, print the number of natural runs (a maximal non-decreasing stretch, or a strictly descending one) from a hand-written counter whose definition is stated, not CPython's own. Compare random input with log2(n!), and print what n < 64 costs.
Then describe what sorted() does (find runs, extend short ones to minrun of 32 to 64 with binary insertion sort, merge runs while galloping when one run keeps winning), and show that sorted input costs exactly n - 1 comparisons at three sizes, with the times printed beside the counts. These counts are CPython's: CPython 3.11 and later chooses the merge order with the powersort rule, and another interpreter or version can differ. Print them from the run, and hard-code none of them.
Some orderings have no score to extract. A black-box judge(a, b) only answers "which of these two is better?", and a sort needs nothing more than that. A comparator returns a negative, zero or positive int, written (a > b) - (a < b), and functools.cmp_to_key wraps it into a key=.
Do three things. First, sort 40 dishes with a hidden taste score using only judge, count its calls, and check the result by peeking at the scores afterwards. Second, sort staff records with mixed directions (department ascending, then salary descending; department ascending, then name descending) three ways: a comparator, two stable passes, and a tuple key where one exists. Third, show that a comparator that always returns 0 leaves the list in its input order. Fuzz all of it, with size 0 included.
key= is called once per item. A comparator wrapped with cmp_to_key is called once per comparison, which is about n log2 n times. Sort 10,000 messy strings by their normalised form (strip, casefold, remove hyphens and spaces) both ways, count every call to normalise, and time both. Then sort 10,000 plain ints with key=None and with a trivial comparator to see the overhead when the work per call is tiny. Print the counts and the times, and say which to prefer from the counts.
sorted(range(n), key=a.__getitem__) returns the indices of a in sorted order (an argsort) without touching a. Use it to reorder a parallel list of big records without moving them while sorting, and invert it to get each item's rank. For ties print three rankings: the ordinal rank (position in the stable order, 0-based), the competition rank (1, 2, 2, 4) and the dense rank (1, 2, 2, 3). Check them against brute-force counts of smaller items, with a fuzz that includes the empty list.
As text, 'file10' sorts before 'file2', because '1' < '2'. A natural order compares the digit runs as numbers. Build natural_key(s) with itertools.groupby and str.isdecimal (no re): split the name into runs of digits and non-digits, turn digit runs into ints, and always start with a text part (possibly ''), so text only ever meets text and ints only ever meet ints. Show the TypeError you get without that rule. Then sort version strings like '1.10.0' by a tuple of ints, and sort case-insensitively with casefold plus an explicit tie-break. Fuzz the key against names built from known parts.
Meetings are half-open [start, end), so a meeting that ends at 10 and one that starts at 10 do not clash. Decide whether one person can attend all of them. Write the O(n^2) all-pairs check, then the O(n log n) version: sort by start, and a clash exists exactly when some meeting starts before the previous one ends. Fuzz them against each other, show that a <= slip and a missing sort each give a wrong answer (with the smallest failing input found), and time both at n = 1,000 and n = 2,000.
What is the fewest rooms that hold every meeting? It equals the most meetings running at once. At the busiest moment k meetings overlap and each needs its own room, so at least k rooms are needed, and the sweep below shows k are enough. DSA Topic 2 swept +1/-1 events with ends before starts. Here sort the starts and sort the ends separately, and walk both with two pointers (DSA Topic 4): a start before the earliest unfinished end needs a new room, otherwise a room just freed is reused. Meetings are half-open, so touching meetings share a room.
Write rooms_two_pointers(meetings). Check it against the event sweep and against a brute force that counts the meetings running at each start time, on a fuzz that includes the empty list, and show the wrong answer from a <= slip. Saying which room each meeting gets needs a heap (DSA Topic 15), named only.
A list of disjoint intervals is sorted and canonical: none overlap or touch (half-open [start, end); two intervals that touch are joined, as in the merge of DSA Topic 2). Insert a new interval without re-sorting: copy the intervals that end before it, absorb every interval that overlaps or touches it, copy the rest. That is O(n). bisect (DSA Topic 3, with its key=) finds the first candidate in O(log n) key calls, but rebuilding the list still copies n items. Fuzz both against "append and re-merge", count the key calls, and time the three at n = 100,000.
Two questions on the same merge. Covered length: the total length of the union of overlapping intervals (half-open): sort by start, merge, add up the merged lengths. Free time: several people each have a list of busy intervals; within a working day [day_start, day_end), find the gaps when nobody is busy. Put all N intervals into one list and sort it once, O(N log N); merging the people's already-sorted lists k at a time with a heap is DSA Topic 15, named. Clip intervals to the day, and fuzz both against a minute-by-minute brute force on small times, including the empty schedule.
A trip is (passengers, pick_up, drop_off), and a passenger is gone at the drop-off time (half-open). The car holds capacity. Report the first time the load is over capacity, or None. Make events (time, change), sort them so drop-offs come first at equal times, and keep a running load. DSA Topic 6 solved car pooling with a difference array because the stops were small indices. Check that both agree on small stops, then show that only the sorted events handle times up to 10^9 and floats: compute the memory the difference array would need, and never allocate it. Show the wrong answer when pick-ups are handled before drop-offs.
Ten statements, each routed to a tool by a rule in code: sorted() with a key, stable passes, counting sort or radix sort (chosen by counted work, n + k against passes * (n + base) against n log2 n), quickselect (one order statistic), k selection passes (when k < log2 n), an interval sweep, or no sort at all (a set, a Counter, one pass). Write route(features), run the tool each statement gets on data of the stated size, and check every result against a plain sorted()-based answer. Print the route and the counted work.
Every comparison sort is, in effect, a decision tree: each comparison is a yes/no branch, and each of the n! input orders has to finish at its own leaf. A tree of depth h has at most 2^h leaves, so some input needs at least log2(n!) comparisons, which is about n log2 n - 1.44 n. This is an argument, not a data structure: you will check it with numbers.
Use # STEP labels and print the evidence:
- Write
insertion_sort(a, log)(in place, returnsNone) andmerge_sort(a, log)(returns a new list, halves[0, mid)and[mid, n)), where each comparison appends its yes/no outcome tolog. Run both on every permutation ofn = 1..8and print the worst case besideceil(log2(n!)). Forn = 9..12print the worst case from the exact formula (n(n - 1)/2for insertion sort, the recurrenceW(n) = W(n//2) + W(n - n//2) + n - 1for merge sort), marked as a formula, and assert that the formulas match the measurements forn <= 8. - Make the leaf argument concrete: for
n = 6, collect the outcome sequence of every permutation and show that all 720 sequences are different. - The same tree also bounds the average: the mean number of comparisons over all permutations of 8 items cannot be below
log2(8!). Print it for both sorts. - Check
log2(n!) >= n log2 n - n log2(e)forn = 10up to10^6withmath.lgamma, and write the one-line proof in a comment (e^n >= n^n / n!). - Count the comparisons
sorted()makes on10,000random items (a wrapper class whose__lt__adds to a counter) and print how far abovelog2(n!)it lands, as a percentage computed from the two printed numbers. - Counting sort never compares two items, so the bound does not apply to it: sort 10,000 wrapped keys in
0..99by counting and print the comparison count (0).
DSA Topic 8 counted inversions (pairs i < j with a[i] > a[j]) with sorted() halves in O(n log^2 n) and named the faster version. Build it now. Merge sort returns each half sorted, and the merge counts the pairs that cross the halves for free: when an item from the right half is taken before the remaining left items, it is smaller than every remaining left item, so add len(left) - i.
Write merge_count(a) (returns a new sorted list and the inversion count, halves [0, mid) and [mid, n), ties taken from the left because equal items are not an inversion) and sorted_halves_count(a) (Topic 8's idea: re-sort both halves with sorted() at every level, then walk them). Use # STEP labels:
- Fuzz both against the
O(n^2)pair count on lists of 0 to 30 items with negatives and duplicates, and show that the count equals the swaps of bubble sort and the shifts of insertion sort. - Count the comparisons of both with a wrapper class whose
__lt__adds to a counter, atn = 10,000and20,000, and decide which does less work from the counts. - Time both on plain ints at
n = 10,000and40,000. Print the times and the ratios, and say what the clock shows without calling a winner when the two are close.
For each index i, count the later items that are strictly smaller: res[i] = #{j > i : a[j] < a[i]}. Sort the indices by value with merge sort. When a left item is placed, every right item already placed is smaller than it and sits later in the list, so add the number of right items placed so far to that item's index.
Write smaller_after(a, strict=True), which returns a new list, with an inner sort_range(lo, hi) on the half-open range [lo, hi) that sorts an index list in place and returns None. Equal values are not smaller, so ties go left; strict=False is the student bug that takes the right item on a tie. Also write smaller_after_halves(a), Topic 8's version that re-sorts both halves with sorted() at every level. Show [5, 2, 6, 1], print the bug on [3, 3, 3] beside the truth, fuzz against the double loop (sizes 0 to 30, duplicates and negatives), and compare the two versions by counted comparisons (a wrapper class with a counting __lt__) at n = 10,000 and 20,000.
How many pairs (i, j) with i < j have lo <= prefix[j] - prefix[i] <= hi, where prefix is the prefix-sum array of a (so that is the number of non-empty subarrays whose sum lies in [lo, hi])? DSA Topic 6 named this and used a sorted list with insort. Merge sort the prefix sums: in the half-open range [l, h) with midpoint mid, before merging, both halves are sorted, and for every left prefix p two pointers into the right half find the prefixes in [p + lo, p + hi]. As p grows, both pointers only move forward.
Write count_range_sums(a, lo, hi, stats) (merge sort of the prefix array, stats counts comparisons and writes) and Topic 6's count_insort(a, lo, hi, stats) with a hand-written counted binary search (comparisons) and the number of moved items per insert. Fuzz the merge version and a bisect/insort version against the O(n^2) loop (sizes 0 to 25, negatives, lo == hi), and compare the counts at n = 5,000, 10,000 and 20,000 on two inputs: a random walk (items in -1000..1000) and an all-negative list, whose prefixes fall below every earlier one, so every insert lands at the front.
Count the pairs i < j with a[i] > 2 * a[j]. Use merge sort on the half-open range [lo, hi), but this time the counting walk must run before the merge, with its own pointer: the condition a[i] > 2 * a[j] does not follow the order in which the merge takes items, so counting inside the merge loop is wrong.
Write reverse_pairs(a) (correct; returns a new count, sorts a copy), reverse_pairs_inline(a) (the student bug: the merge loop takes the right item when left[i] > 2 * right[j] and counts there) and reverse_pairs_as_inversions(a) (the other bug: the inversion count of the previous question with a[i] > a[j]). Fuzz all three against the O(n^2) loop (sizes 0 to 25, negatives and duplicates) and count how many fuzz cases each bug gets wrong. Then search lists by length and value for the smallest failing input of each bug, strictly shorter first, and print it beside the truth. Finally time the correct version against the double loop at n = 1,000 and 2,000.
DSA Topic 8 split the points by x and re-sorted the strip by y with sorted() at every level, which is O(n log^2 n), and named the fix. Build it. Sort the points by x once. solve(lo, hi) works on the half-open range [lo, hi) and returns its points merged by y, so the strip is an O(n) filter of an already y-sorted list. Distances are compared squared, so everything stays in exact integers.
Write closest_pair(points) and closest_pair_sorted_strip(points) (Topic 8's idea). Points are objects with x, y and a counting __lt__ that compares y, so sorted() and the merge are both counted. Raise ValueError for fewer than 2 points. Fuzz both against the O(n^2) brute force (sizes 0 to 40, many duplicate and collinear points; compare the distance, since several pairs may tie) and check that the returned pair really has that distance. Then compare the counted y-comparisons and distance checks at n = 10,000 on two shapes: uniformly random points, and points on one vertical line (every x equal, y distinct), where the strip holds every point at every level. Print the times beside the counts, with no verdict from the clock.
Arrange non-negative integers so that their concatenation is the largest number, returned as a string. Put a before b when a + b > b + a as strings, using functools.cmp_to_key. A comparator must be consistent (antisymmetric and transitive) or the sort is meaningless, and this one is, because it hides a real-valued key.
Use # STEP labels:
- Write
largest_number(nums)with the comparatorcmp_concat(a, b)returning(b + a > a + b) - (b + a < a + b)on strings. All zeros give"0", and an empty list gives"". - Derive the key in comments. With
A = int(a),B = int(b)and lengthsla,lb:a + bisA * 10^lb + Bandb + aisB * 10^la + A, soa + b > b + aexactly whenA * (10^lb - 1) > B * (10^la - 1), that isA / (10^la - 1) > B / (10^lb - 1). Writelargest_number_key(nums)withFraction(int(s), 10**len(s) - 1)(sorted descending), and print the keys of[3, 30, 34, 5, 9]. - Check the comparator's sign against the
Fractioncomparison on 20,000 seeded pairs. - Fuzz both against brute force over all permutations (
itertools.permutations) for lists of 0 to 7 items, with many prefixes and zeros. - Print the two naive sorts that fail (descending as text, and descending as numbers) beside the truth on an input where each fails, and the number of comparator calls against the number of keys.
DSA Topic 7 sorted (-count, value) to get the k most frequent values and named bucket-by-count for this topic. A value's count is between 1 and n, so put each distinct value in buckets[count] (a list of n + 1 lists) and read from the top count downward until k values are taken. Ties are broken by smaller value first, so each bucket you read is sorted.
Write top_k_buckets(values, k) (returns a new list) and top_k_sorted(values, k) (Topic 7's sort). Fuzz both against each other and against Counter.most_common (which breaks ties by first appearance, so compare the counts, and check that every returned value has at least as high a count as any value left out), with sizes 0 to 60 and k from 0 to past the number of distinct values. Then count the key comparisons of both (wrapper classes with counting __lt__) on two inputs of 50,000 values: a heavy-tailed one (most values rare, a few frequent) and one where every value is distinct. Print what you measure, including the case where the buckets do not help.
DSA Topic 7 grouped anagrams in a dict keyed by a signature. Do it without hashing: build (signature, word) pairs, sort them, and cut the runs of equal signatures in one scan with itertools.groupby. The signature is the word's letters in order. sorted(word) costs O(k log k) for a word of k letters. A counting pass over 26 slots costs O(k + 26).
Write group_by_sorting(words, signature) (returns a new list of groups, each group sorted, groups sorted by their first word), signature_sorted(word) and signature_counted(word) (26 counters, then the letters rebuilt in order; lowercase a to z only), plus Topic 7's group_by_dict(words). Fuzz all four combinations against each other on 0 to 40 words including '' and repeated words. Time group_by_sorting with both signatures and the dict version on 20,000 words of 6 letters from an alphabet of 5 (many anagrams), and the two signature functions alone on words of 8 and 2,000 letters. Print the work formulas k log2 k and k + 26 for those lengths beside the times, and print the time ratios, with no winner called.
Two questions with two answers. With distinct values, how few swaps sort the list when (a) any two positions may be swapped, and (b) only adjacent positions may?
(a) The answer is n - cycles. Sort the indices by value (an argsort): order[t] is the index whose item belongs at position t, which is a permutation, and it splits into cycles. A swap changes the number of cycles by exactly one (it splits one cycle or joins two), and the sorted list has n cycles, so at least n - cycles swaps are needed. A cycle of length L can be fixed with L - 1 swaps, so that many suffice. (b) An adjacent swap changes the inversion count by exactly one, and the sorted list has none, so the answer is the inversion count.
Write min_swaps_any(a), min_swaps_adjacent(a) (inversions by merge sort, O(n log n)), sort_by_any_swaps(a) and sort_by_adjacent_swaps(a), which perform the swaps on a copy and return (sorted list, swaps made). Check the formulas against the performed swaps on 300 seeded permutations (sizes 0 to 9). Check them against brute force over swap sequences (itertools.product over the allowed swaps, trying 0 swaps, then 1, then 2, and so on) for every permutation of n <= 5 for any swaps and n <= 4 for adjacent swaps. Finally show that with duplicates the argsort formula can be wrong: print [2, 1, 2, 1] beside the true minimum from brute force.
Rearrange a list into a wiggle: a0 <= a1 >= a2 <= a3 ... (non-strict), or a0 < a1 > a2 < a3 ... (strict).
- Non-strict, two ways. Sort, then swap each neighbour pair
(1, 2),(3, 4), ... inO(n log n); or one pass that swaps any neighbour pair facing the wrong way, inO(n). Write the proof that the pass never breaks the pair before it. - Strict: sort, split at the middle, and interleave the two halves from the back: small half on even positions, large half on odd positions. Sorting and swapping pairs is not enough once values repeat, so print one input where it fails.
- A value that appears more than
(n + 1) // 2times can never be placed (equal values cannot touch). Is that count the whole story? Do not assume. Confirm the strict method against a brute force over every permutation, for every multiset of up to 7 items from a small value range (the empty list and one item included): it must find an arrangement exactly when one exists.
A researcher has an h-index of h if h of their papers have at least h citations each. Given the citation counts, find the largest such h.
- Sort descending and find the last position
iwherec[i] >= i + 1:O(n log n). - Count papers per citation value, capped at
n(a paper with 900 citations still counts as "at leastn", becausehcan never exceedn), and scan down fromn, adding up papers until the running total reachesh:O(n), a counting sort that never needs the largest citation value.
Check both against the definition on seeded lists, including the empty list, all zeros and huge values. Time both at n = 200,000 and print the numbers.
Friends live at positions x_1 ... x_n on a line. Where should they meet so the total distance sum of abs(x_i - p) is smallest?
- Show with a comment-proof that the best
pis a median:f(p + 1) - f(p) = (points at or left of p) - (points right of p), sofkeeps falling until half the points are behind you. - Find the median in average
O(n)with a quickselect loop that makes copies, and check the cost against trying every integerpbetween the smallest and largest point, on seeded inputs including the empty list. - For an even
n, everypbetween the two middle values ties. Check that the set of best integer points is exactly that interval. - On a grid with Manhattan distance
abs(r - pr) + abs(c - pc), rows and columns do not interact, so use two medians. Check against a search of every cell in the bounding box.
At n = 100,000 print how many cost evaluations "try every p" would need, computed and never run.
Sorting does not always mean "smallest first". Three jobs where the order is given to you:
- A ranking.
rankis a dict item -> position (0, 1, 2, ...). Items in the ranking come first, in rank order; unknown items go last in ascending order. The key is(rank.get(x, len(rank)), x). It only works while the ranks are0 .. len(rank) - 1: show what a 1-based ranking does to it, then fix it with a key that cannot collide. - A custom alphabet. Sort words by a given letter order with
key=[pos[c] for c in w]. Compare withsorted(reverse=True)on a reversed alphabet: they differ on a prefix pair such asappandapple. - Evens before odds, stably with
key=x % 2, and the bug that puts odds first.
Check each against an explicit loop on seeded inputs.
A list is k-sorted when every item is at most k places from where it belongs in the sorted order (and its values are distinct). Insertion sort is O(n + inversions), so how slow is it on such a list?
Write the proof as comments: an inverted pair i < j has j - i < 2k, so each position is in at most 2k - 1 inversions with a later one, so there are at most n(2k - 1) inversions and insertion sort is O(nk).
Build k-sorted inputs by shuffling each block of k + 1 consecutive sorted values, and assert the property. For k = 1, 10, 100 at n = 10,000 print the shifts, the bound, shifts per n * k, the comparisons sorted() makes (through a counting wrapper) and both times. For contrast, a fully random list at n = 2,000. A heap holding k + 1 items gives O(n log k) (DSA Topic 15), named only.
A file of numbers is too big to hold in memory. Simulate that with a budget of 1,000 numbers at a time, and sort a file through temporary files.
- Phase 1. Read the input a chunk of
budgetlines at a time, sort each chunk withsorted(), and write each sorted run to its own file. - Phase 2. Merge the runs two at a time, streaming line by line (the two-pointer merge of two sorted lists, holding one line from each file in memory), pass after pass, until one run is left. That takes
ceil(log2(runs))passes. An odd run is carried to the next pass untouched.
All the files live in a tempfile.mkdtemp() sandbox that is removed in a finally. Count lines read, lines written and comparisons. Check the output against sorted(all) for inputs of 0, 1, 999, 1,000, 1,001, 2,000, 2,500 and 6,500 numbers, and with duplicates and negatives. A one-pass k-way merge would pick the smallest of all the runs' heads with a heap (heapq.merge, DSA Topic 15), named only.
Strings compare character by character by code point, so a few orders surprise people.
'Z' < 'a','10' < '9', and an accented letter sorts after'z'. Print each (build the accented letter withchr()and print withascii()).- Case-insensitive order:
key=lambda s: (s.casefold(), s). The second element breaks ties, so'a'and'A'have a defined order.casefoldalso folds the German sharp s (code point 223) toss, whichlower()does not. - Length first, then alphabetical:
key=lambda s: (len(s), s). - Numbers stored as text:
key=int(negatives included), against the text order. - The cost of a comparison. Comparing two strings costs up to their common prefix. Sort strings of length 100 that differ at once, and strings that share a 90-character prefix; count the characters examined through a wrapper class and print the average per comparison, then time
sorted()onn = 20,000strings of length 500 in both shapes.
Check the keyed sorts with a hand-written insertion sort driven by an explicit "comes before" rule.
Sorting is the first tool many people reach for, and often the wrong one. For each task below, write the sort-first answer and the right-tool answer, check that they agree, and print the work each did (comparisons for the sorts, item visits for the tools) with the verdict computed from those counts:
- The smallest and the largest item: sort, against one pass.
- The most common item (ties: the smaller value): sort and scan runs, against
Counter(DSA Topic 7). - Does the list hold a duplicate: sort and compare neighbours, against a
set(DSA Topic 7). - The k-th smallest: sort, against a quickselect loop that makes copies.
- Are two strings anagrams: sort both, against 26 counts.
- A running median (the lower median,
s[(t - 1) // 2]) after every item of a stream of 300: re-sort the prefix each time, against keeping one list sorted withbisect.insort. Keeping two heaps does it inO(log n)per item (DSA Topic 15), named only. - When sorting does pay:
qqueries "how many items are<= x", answered by scanning every time or by sorting once and usingbisect. Print the break-evenqas a computed number and test oneqfar below it and one far above.
Count the comparisons sorted() makes with a small wrapper class. Time both ways beside the counts, with no verdict from the clock.
The maximum gap is the largest difference between neighbours in sorted order. Sorting gives it in O(n log n); the pigeonhole principle gives it in O(n) without sorting.
nintegers spanS = max - min, and haven - 1gaps between sorted neighbours, so the largest gap is at leastS / (n - 1), and (integers) at leastw = ceil(S / (n - 1)).- Put each item into the bucket
(x - min) // w. Two items in one bucket differ by at mostw - 1, which is less thanw, so the largest gap never lies inside a bucket. There areS // w + 1 <= nbuckets. - Keep only each bucket's minimum and maximum, then scan the non-empty buckets in order: the answer is the largest
(bucket min) - (previous non-empty bucket's max).
The plan form is n - 1 buckets of width S / (n - 1) in floats; the integer width ceil(S / (n - 1)) avoids rounding errors. Fuzz against sort-and-scan (empty, one item, two items, all equal, negatives). Show a plausible bug, comparing with the previous bucket's min, and print the shortest failing input found by the fuzz beside the truth. Time n = 100,000.
How far behind sorted() is a hand-written sort? Measure it, and read the answer off your own numbers, never a remembered multiplier.
Write compact versions that each return a new list (the quadratic ones work on a copy): merge sort, three-way quicksort with a random pivot that recurses into the smaller part, counting sort, LSD radix sort (base 256) and bucket sort for integers. At n = 10,000 time them on random, sorted, reversed and few unique (values 0 to 9) inputs and print the time and the ratio to sorted() in one table. In a second table, bubble sort with early exit, selection sort, insertion sort and Shell sort at n = 1,000 (the quadratic sorts are slow, and 1,000 already shows the pattern). Time each on a fresh copy made inside the timed function. Check every output against sorted().
Print the smallest and the largest ratio from each table, and when you would still write your own: linked data (DSA Topic 12), data on disk, a stability or memory need, or an interview.
Every fixed pivot rule has an input that makes quicksort quadratic. First-item and last-item pivots fall on sorted and reversed input. Median of three survives those, but it has a bad input too, and you can find it by counting rather than guessing.
Write quick_sort(a, rule, stats): Lomuto on a closed range [lo, hi], in place, returns None, and records comparisons in stats. The rule is "first", "last" or "median3" (median of the first, middle and last items, counted as 3 comparisons). The chosen pivot is swapped to a[hi] before partitioning.
- At
n = 800, count comparisons for"first"and"last"on sorted input only, as the stand-alone baseline. Then count"median3"on sorted, reversed, rotated (1..n - 1then0) and evens-then-odds. Print each count as a fraction ofn(n - 1)/2, and find median of three's worst shape from the table. - Prove that worst case is quadratic by doubling:
n = 200, 400, 800on the two killer shapes (rotated and evens-then-odds), printing the ratio between consecutive counts beside whatn log2 nwould give. - Run the first-item rule on sorted input at
n = 2,000and catch the error, printing only its type name.
Few distinct values break Lomuto even with a random pivot. With a[j] < pivot, every item equal to the pivot stays on the right; with a[j] <= pivot, every one goes left. Either way an all-equal part is split 0 and m - 1.
Write four in-place sorts on closed ranges [lo, hi], each returning None and counting comparisons:
lomuto_lt(a, stats, rng)andlomuto_le(a, stats, rng): a random pivot moved toa[hi], then<or<=;hoare(a, stats): middle pivot, scans that stop on items equal to the pivot, recursing on[lo, j]and[j + 1, hi];three_way(a, stats, rng): a random pivot and the<,==,>split, recursing only on the<and>parts.
Fuzz all four (empty list included, any exception counted as a failure). Then at n = 800 centre the table on lomuto_lt against lomuto_le, for all-distinct input and for k = 10, 2, 1 distinct values (each value equally often), and print n^2 / (2k) beside each count with the measured/predicted ratio. Add one summary row each for hoare and three_way on the k = 2 input.
Hoare's partition returns j, and the caller recurses on [lo, j] and [j + 1, hi]. That split is safe only when j < hi always holds. Take the pivot from a[hi] and run [1, 2]: i stops at index 1, j stops at index 1, so j == hi, and the call on [0, 1] calls itself on [0, 1] again, forever.
Write quick_sort(a, pivot_at, split, max_depth=None): in place, returns None, closed ranges. pivot_at is "hi", "lo", "lower mid" ((lo + hi) // 2) or "upper mid" ((lo + hi + 1) // 2). split is "j" ([lo, j], [j + 1, hi]) or "i" ([lo, i - 1], [i, hi]). max_depth is a guard for the fuzz: it raises RecursionError past that depth so a broken variant fails fast.
Show the plain RecursionError on [1, 2], printing its type name only. Then fuzz six combinations over every list of length 0..6 with values 0..2, plus seeded random lists, and print each one's failure count and smallest failing input.
Three bugs that hide behind ties. Each returns a new list.
merge_sort(a, key, bug): half-open ranges[lo, hi). The bug takes from the left only onkey(left) < key(right), so on a tie it takes the right item first.two_key_sort(records, primary, secondary, bug): a stablesorted()pass on the secondary key, then a hand-written pass on the primary key. The bug writes that pass as Shell sort with Knuth gaps (1, 4, 13, ...); the fix uses insertion sort (the gap 1 alone).radix_sort(a, bits, bug): LSD base 2 on non-negative ints. The bug splits each bit with DSA Topic 2's in-place two-pointer swap partition; the fix builds a zeros list and a ones list.
Fuzz each on plain ints, then on records (key, key2, label) against sorted(records, key=...), which is the only stable answer. Print each bug's smallest failing input from an exhaustive search, its output and the truth. Then show the fixes pass.
A leaderboard wants score descending, then name ascending. Four attempts on a list of Player(name, score) records:
- (a)
sorted(players, key=lambda p: (p.score, p.name), reverse=True); - (b)
sorted(players, key=lambda p: p.score)[::-1]; - (c)
sorted(players, key=lambda p: (-p.score, p.name)); - (d) two stable passes:
sorted(players, key=name), thensorted(..., key=score, reverse=True).
Write ranked_ok(original, out), which checks that out is a permutation of original and that every adjacent pair follows the rule, written as an explicit if chain. Print each attempt on a crafted board with ties. Then fuzz 500 boards with all scores distinct and 500 with scores 0..4, and count the boards on which each attempt fails.
Every ordering comparison (<, <=, >, >=) and == with float("nan") is False; only != is True: nan < x, x < nan and nan == nan alike are False. A sort assumes a total order, so with a NaN in the list it can return a list that is not sorted, and it raises nothing.
- Print
sorted([3.0, nan, 1.0, 2.0, 0.5])and check it withordered_ignoring_nan(xs), which asks whether the non-NaN values are in order. - Put the NaN at each of the 5 positions of the same list and print every result: the output depends on where the NaN starts.
- Fuzz 1,000 seeded lists of length
0..12with one NaN and count the unsorted results. Then fuzz two fixes:key=lambda x: (math.isnan(x), x), which puts NaNs last, and filtering them out first. - Show that
max()has the same problem, and thatNoneamong ints raisesTypeErrorinstead.
functools.cmp_to_key(cmp) trusts cmp to describe a consistent order: cmp(a, b) is negative, zero or positive, flips sign when the arguments swap (antisymmetry), and chains (if a <= b and b <= c then a <= c, transitivity). Three comparators that break the deal, each with no error raised:
lambda x, y: x > yreturns abool, so1or0, never negative. Sort[3, 1, 2, 5, 4]with it.lambda r, s: 1 if r[0] > s[0] else -1never returns 0, so for equal keys bothcmp(a, b)andcmp(b, a)say "less". Sort records with tied keys and compare withsorted(key=).- Rock, paper, scissors: each beats one other. Sort the three in two different input orders.
Then write check_laws(cmp, items), which tests antisymmetry on every pair and transitivity on every triple of items, and returns the first broken law with its witness, or None. Run it on the three liars, on a correct numeric comparator, and on the largest-number comparator (a + b against b + a as strings) over 12 seeded numbers.
counts[x] += 1 with x = -2 raises nothing in Python. A negative index counts from the end, so it quietly adds to a slot near the end of the counts list. In C the same line writes outside the array.
Write counting_sort_naive(a) (counts sized max(a) + 1) and run it on [3, -2, 1, 0, 2], printing the result beside the truth and both lengths. Then show that a key past the range does raise: run counting_sort_k(a, k) (a fixed [0] * k) with k = 10 on a list containing 10, and one containing -11.
Fix it: counting_sort(a) offsets every key by the minimum, and counting_sort_range(a, lo, hi) checks the declared range first and raises ValueError. Both return a new list. Fuzz the naive version and the fix on 1,000 seeded lists with negatives (empty included), and count three outcomes for each: right, silently wrong, raised.
Textbook bucket sort for n floats in [0, 1) puts x in bucket int(x * n). Write bucket_sort_naive(a, stats), which returns a new list, insertion sorts each bucket and counts shifts. Show three edges, each beside the truth:
x = 1.0lands in bucketn:IndexError.x = -0.15withn = 10lands in bucketint(-1.5) = -1, Python's last bucket: wrong, and no error.- Clustered input (every value below
0.0005) puts everything in bucket 0: shifts atn = 500, 1,000, 2,000.
Then write bucket_sort(a, stats): normalise by (x - min) / (max - min) (returning a copy when max == min), clamp the index to n - 1, and check the bucket sizes: a bucket above 32 items is sorted with list.sort() instead of insertion sort, counted as a fallback. Show that normalising alone does not save the clustered input once one outlier stretches the range. Fuzz both versions on 600 seeded lists, empty included.
Two merge sorts that are correct and still slow, because each merge step copies or shifts a list:
merge_sort_concatbuilds the output without = out + [x], which makes a new list and copies all ofoutat every step;merge_sort_poptakes items withleft.pop(0)/right.pop(0), which shifts every remaining item one slot left.
A merge of m items then costs about m^2 / 2 element copies for concat and about m^2 / 4 for pop(0); both are quadratic, not m. Write both, plus merge_sort_index (append and two indices), each returning a new list over half-open ranges [lo, hi). Each records copies in stats: one per element written, copied or shifted, which is exactly what the list operations do.
- Check all three against
sorted()on seeded lists, sizes0..40included. - Print
copiesforn = 1,000, 2,000, 4,000, 8,000with the ratio per doubling, besiden log2 n. - Time one top-level merge of two sorted halves by doubling, and print the time ratios.
pop(0)is a fast Cmemmovein CPython, so it needs bigger sizes before its curve shows.
Four sorting mistakes look harmless and give nothing sensible. Reproduce each one, print what happens, and fix it.
- A
key=function that appends to the list being sorted. - A key that raises on one item (
inton"n/a"): is the list left half sorted? - A key that reads a dictionary which changes between calls (a "clock" that ticks on every call).
- A key that returns
rng.random()(a seeded random number).
For 3 and 4, say what rule a key must follow, and write a small is_pure(key, items) check that calls the key twice per item.
Quickselect finds the k-th smallest item without sorting everything. It has three bad days, and a fuzz test finds each one.
Write select_index(a, t, rule, stats, rng=None): Lomuto on the closed range [lo, hi], a loop (no recursion), on a copy, returning the item that would sit at 0-based index t once sorted. rule is "first" or "random". Count comparisons in stats.
- First-item pivot on sorted input, finding the largest item: count comparisons at
n = 500andn = 1,000, print each as a fraction ofn(n - 1)/2, and the doubling ratio. - Lomuto with a random pivot on all-equal input: count again, and show the same random pivot is fine on sorted input.
kth_smallest_bug(a, k)callsselect_index(a, k, ...)instead ofk - 1. Fuzz it againstsorted(a)[k - 1]and print the failure count and the first failing case.- Write
select_three_way(a, t, stats, rng)(random pivot, Dutch national flag partition, count every<and>the code makes) and repeat 1 and 2. Name median of medians, which guarantees O(n).
Whether two intervals "touch" depends on the convention, and three bugs come from forgetting which one is in force.
Convention first. Meeting times are half-open [start, end): a meeting ending at 10 and one starting at 10 do not clash. Whole-day bookings are closed [first_day, last_day]: days 1-2 and 3-4 are adjacent, and a calendar joins them into days 1-4.
rooms_buggy(meetings): a +1/-1 sweep that sorts starts before ends at equal times (the same slip as Q46, now as the event tie order).merge_days_buggy(ranges): merges closed day ranges only when they overlap (start <= end).rooms_closed_buggy(days): feeds closed day ranges to the half-open sweep unchanged (a one-day booking[3, 3]is an empty interval).
Fix each. Fuzz every function, buggy and fixed, against a brute force on a time grid (count the occupied units yourself), and print one counterexample per bug.
Three benchmarks of sorting give nonsense, and each prints a confident number. Reproduce them.
best_of(lambda: data.sort())times an in-place sort. Print the time of each of the three runs separately, and count comparisons for the first run and the second on the same list with a counting wrapper (n = 10,000).- Time a hand-written merge sort on random data against
sorted()on data that is already sorted. Print the input shape beside each time, then redo it fairly on the same input. - Time
sorted(data)(which copies) againstdata.sort()(which does not) on sorted data, and say what the gap is made of without subtracting two minimums.
State the fix: copy inside the timed function, for both, and print the input shape.
Write one checker, check_sort(fn, declared_stable), for any function fn(a, key=None, reverse=False) that returns a new list. For each input it checks five things separately:
- ordered: the output is in order under
key; - perm: the output is a permutation of the input (
Counterequality); - stable: equal keys keep their input order (skipped when the sort declares itself unstable);
- matches: the output equals
sorted(a, key=, reverse=)exactly; - crash: no exception, including
RecursionErrorfrom a partition that never shrinks.
Run it on seeded inputs: empty, one item, all equal, sorted, reversed, organ pipe, few unique, negatives and random, each with reverse=False and reverse=True (records are (value, index) so stability is visible). Then run it on sorted(), a correct merge sort, and five broken sorts: an unstable merge, a partition that never shrinks, an insertion sort that stops at index 1, a comparator that returns a bool, and a counting sort that meets negative keys. Print a table of which property caught each bug. Finish with the NaN trap: show why the suite must refuse NaN input.
Build a lab that puts every sort in this topic behind one interface and measures them side by side.
lab_sort(name, a, key=None, reverse=False, stats=None)returns a new list and fillsstatswithcomparisonsandwrites.- The sorts: bubble, selection, insertion, Shell, merge, quick (random pivot, three-way partition, closed ranges), counting and LSD radix (integer keys). Each has a declared
stableflag, and the lab verifies it on(key, index)records. - Run on six shapes (random, sorted, reversed, nearly sorted, few unique, all equal) at
n = 600. - Print one table each for comparisons, writes and milliseconds. For each shape name the hand sorts with the least counted work (comparisons plus writes), and give
sorted()as the baseline with its ratio to the fastest hand sort.
Counts are the evidence. The clock is printed beside them.
Build an introsort-style hybrid: quicksort with a median-of-three pivot (Lomuto, closed ranges [lo, hi]), insertion sort for parts under 16 items, and a depth limit of 2 * floor(log2 n) after which the part is merge sorted. (C++'s introsort switches to heap sort, DSA Topic 15; it is named, not built.) It sorts in place and returns None.
- Compare against plain quicksort (the same median-of-three Lomuto, no cutoff, no limit) on random, sorted, organ pipe, all-equal and an adversarial input at
n = 800. Build the adversary against plain quicksort with a comparison oracle that decides item values lazily, so no hand-made killer sequence is needed. Print comparisons, deepest partition depth and milliseconds, withsorted()as the baseline. - Print the hybrid's comparisons divided by
n log2 nat three sizes on random input. - Argue the O(n log n) worst case in a comment.
Build a leaderboard for players (name, score, time). Rank by score descending, then time ascending, then name ascending.
board_keys(players)returns the sorted list of(-score, time, name)keys. Top 10 is its first 10 items.- Players with equal
(score, time)share a rank. Competition rank skips after a tie (1, 2, 2, 4); dense rank does not (1, 2, 2, 3). Give each in O(log n) per player withbisecton sorted lists, and check against a brute-force count for 300 players. - Add new players two ways:
bisect.insortone by one, andextendplussort()once per batch. Measure batches of 1, 100 and 10,000 players applied to a board of 20,000, and name a winner only when the gap is at least 1.5x. Count the elementsinsortmoved as well. - Check every result against a full sort.
Build a booker for one day (minutes 0..1439). Meetings are half-open [start, end), so a meeting ending at 10:00 and one starting at 10:00 do not clash. Seed 15 requests, starting on quarter hours between 08:00 and 17:00 and lasting 30 to 120 minutes.
- STEP 1: book requests first-fit into 4 rooms. Each room keeps its starts and ends in sorted lists, and
bisectchecks a slot in O(log n). - STEP 2: the fewest rooms for the whole day, from a +1/-1 sweep with ends before starts.
- STEP 3: assign meetings to rooms: sort by start, reuse the room that frees earliest (found by a scan of the rooms; DSA Topic 15's heap makes that O(log rooms)). The room count must equal the peak.
- STEP 4: the merged busy times, and every free slot of at least 60 minutes.
- STEP 5: fuzz every function against a minute-grid brute force.
A file of 100,000 seeded lines does not fit in memory; only B lines do. This reuses the pipeline of the earlier external-sorting question (Q66): pass 0 writes sorted runs of B lines, then runs are merged line by line. Keep that part short and build what is new, inside a tempfile.mkdtemp() sandbox.
- One merge function,
kway(paths, out, st), that scans theFcurrent heads for the smallest, O(F) per output line. WithF = 2it is the pairwise merge. (heapq.mergedoes this in O(log F) per line, DSA Topic 15; named only.) merge_all(runs, fan_in, ...): merge groups offan_inruns per pass until one file remains. A trailing single run is carried over with no I/O.- For
B = 1,000,5,000and20,000and fan-in2,4andR(all runs at once), print passes, lines written and merge comparisons per line, next to the predicted passes1 + ceil(log_F R). Check every output againstsorted(). - Show the condition on
Bthat lets oneR-way pass work, and check with a counting wrapper that scanningFheads makesF - 1comparisons.
Build a record sorter driven by a text spec such as "dept asc, salary desc, name asc natural". Rows are dicts with dept, name (text), and salary, age (ints), and any field may be None.
parse_spec(text)returns a list of(field, descending, natural)and raisesValueErroron an unknown field, on bothascanddesc, or onnaturalfor a number.sort_by_passes(rows, spec)returns a new list using one stablelist.sortper key, last key first, so earlier keys win ties. A descending text key needs no trick here, becausereverse=Truekeeps equal items in input order. Missing values go after the present ones in every pass, in both directions.naturalcompares digit runs by value and text case-insensitively (emp2beforeemp10). Split the runs withitertools.groupbyandstr.isdigit.
Check it two ways: against one tuple key (numbers negated for desc) wherever such a key exists, and against a cmp_to_key comparator for every spec. Show that a spec with a descending text key has no tuple key made by negating fields, because - does not apply to str. Run the passes in the wrong order (first key first) and show the wrong result. Fuzz 400 seeded specs and tables with ties and Nones. Finally, at n = 20,000, count key calls against comparator calls and time the passes, the tuple key and the comparator.
Build an order-statistics toolkit on one quickselect: a loop (no recursion), a random pivot from a seeded random.Random, and a three-way partition on a closed range [lo, hi] of a copy, so the input is never changed.
select(a, k, rng): the k-th smallest, counting from 0. It raisesIndexErrorwhenkis outside0..n - 1.median(a, rng): the middle item, or the mean of the two middle items, the same values asstatistics.median.percentile(a, p, rng): the nearest rank, which is the item at rankceil(p * n / 100)(at least 1) of the sorted list.k_smallest(a, k, rng): the k smallest in order, inO(n + k log k).kth_largest(a, k, rng).
Fuzz every tool against sorted() and statistics (median, and median_low for the 50th percentile) on seven shapes: one item, all equal, sorted, reversed, few unique, negatives with duplicates, and random. Then count the comparisons for the median at n = 10^3, 10^4, 10^5, on random and all-equal input, against the comparisons sorted() makes. Time both at 10^5. Name median of medians as the guaranteed-linear option, and say why libraries rarely use it.
Draw sorting as text. Take 12 seeded values in 0..9, and draw each as one character of ' .:-=+*#%@' (0 is a space, 9 is @). Print one line per frame with a label, the drawing between bars, and the comparisons made so far:
- bubble sort: one frame per pass, stopping early on a pass with no swap;
- selection sort: one frame per pass;
- insertion sort: one frame per inserted item;
- bottom-up merge sort: one frame per width;
- quicksort (Lomuto, closed ranges
[lo, hi], smaller side recursed): one frame per partition.
Every frame must be checked against its algorithm's invariant before it is printed. After bubble pass p, the p largest are home. After selection pass p, the p smallest are home. After insertion step i, the first i + 1 items are sorted and are the original first i + 1. After merge width w, every block of 2w is sorted. After a partition, everything left of the pivot is smaller and nothing to its right is. Every frame is also checked to be a permutation of the input. Run the same checks silently on 300 more seeded rows, and show that the checks catch a bubble sort whose passes stop one pair short. Keep the output under 60 lines.
Write sort_ints(a, stats), which returns a new sorted list of ints and picks its method from n and the key range:
- counting sort over
min..max(negatives shift down to slot 0), costing about2n + ksteps forkslots; - LSD radix sort, base 256, on
v - min, costingd * (2n + 256)steps fordbyte passes; sorted(), at aboutn log2 ncomparisons.
It chooses the method with the least counted work. Print the thresholds this implies (the largest k and the most radix passes that still beat sorted() at n = 10^3, 10^4, 10^5). Then run six workloads: 10^5 in 0..100, 10^5 signed 32-bit, 10^4 in 0..10^6, 50 in 0..10, 10^3 in 0..10^18, and 10^5 in +-10^30. For each, print the method, its estimate, the work it really counted (the comparisons, through a counting wrapper, when it chose sorted()), and its time beside sorted()'s time. Say honestly what the clock does to a choice made by counts. Fuzz the chooser and each method against sorted() on negatives, duplicates, huge ranges, all-equal lists and long lists, counting exceptions as failures.
Five items have 5! = 120 orders, and log2(120) is about 6.9, so every comparison sort needs 7 comparisons on some order. Can you always do it in 7?
- Measure the worst case of insertion sort, top-down merge sort and binary insertion sort over all 120 orders, with a counting
less(x, y). - Write
sort5(items, less)from this plan. Sort the two pairs(a, b)and(c, d), then order the pairs by their larger items. That gives a chaina < b < dwithc < d. Inserteinto the chain of 3 by binary search, then insertcby binary search among the items beforedonly. Check it on all 120 orders and on all3^5inputs with ties, and print how many orders need 6 and how many need 7. - This is the
n = 5case of Ford and Johnson's merge-insertion. Tabulateceil(log2(n!)), merge-insertion's countF(n) = sum of ceil(log2(3k/4)) for k = 1..n, binary insertion'ssum of ceil(log2 k), and merge sort'sW(n) = W(floor(n/2)) + W(ceil(n/2)) + n - 1forn = 1..12. Confirm the last two by brute force over alln!orders forn <= 7, and print where merge-insertion misses the bound.
The interviewer says: "Tell me about sorting." In a few minutes, cover the quadratic sorts and when they win, merge sort and quicksort with their best, average and worst cases, the comparison lower bound, the linear-time sorts and what they assume, stability, and what sorted() really does. Back every claim with a few printed lines from code you run, not from memory, and finish with the hand-written sort against sorted() on the clock.
You are shown four buggy sorts. For each one, reason first: write down what it does wrong and the smallest input that shows it. Then run the code to confirm. Every bug here gives a wrong result or raises, so check that your input really is the smallest by a brute-force search over short inputs, shortest first.
- An insertion sort whose inner loop stops at index 1 (
while j > 1 and ...). - An LSD radix sort, base 2, whose stable passes run from the highest bit down.
- An index-based bottom-up merge sort that sets
mid, hi = lo + w, lo + 2 * wwithout clamping them ton. Which lengths fail? - A selection sort whose scan is
for i in range(p + 1, n - 1).
Print each prediction beside the observed result, and show each fix passing a seeded fuzz. (The ties-right merge, strict < Lomuto on all-equal input, counts[-2] and the bool comparator were diagnosed in Q74, Q72, Q78 and Q77.)
For each workload, pick the method, then back the pick with counted work and a timing. Give a clock verdict only where the measured ratio is 2x or more.
10^6ints in0..1,000.10^5records that need a stable two-key order (region, then day, ties in arrival order).- A nearly sorted log of
10^5timestamps (100 adjacent swaps). - Data over the memory budget: 20,000 lines with room for 2,000 in memory (in a
tempfile.mkdtemp()sandbox). - The top 10 of
10^6. - A black-box comparator, where each call is the expensive part: compare
sorted(key=cmp_to_key(cmp)), merge sort and random-pivot quicksort by calls, againstlog2(n!).
A mock interview, one question and its follow-ups:
- "Find the k-th largest item." Start with the sort, which is also your oracle, and handle a bad
k. - "Can you beat
O(n log n)?" Quickselect's comparisons againstsorted()'s, in one line (built in Q92 and Q33). - "What is the worst case?" The first-item pivot on sorted input, in one line beside its prediction
n(n - 1)/2(Q82). - "What about duplicates?" Two-way Lomuto on all-equal input, in one line beside the sum of
n - 1 - loforlo = 0..n/2(Q33). - "The items now arrive as a stream." Keep the k largest so far in a sorted list. Count the replacements against their expectation,
k ln(n/k), and show the rising stream that makes every item a replacement. Name what DSA Topic 15 changes. - "When would you still sort?" Find the number of queries on the same data after which sorting once does less work than repeated quickselect, for both the three-way and the two-way partition.
Build a report engine for a seeded event log. Each event has user, start, end (half-open [start, end) in seconds), score (0 to 100) and region.
- Sort specs. A text spec like
"region asc, score desc, user asc"is parsed, with errors rejected, and applied as stable passes, last key first. For each pass the engine picks counting sort when the key is an integer and2n + k < n log2 nforkdistinct slots, andsorted()otherwise. Counting sort must stay stable in the descending direction too. - Memory budget. When the rows exceed a budget, the engine sorts runs of at most
budgetrows, writes them to files in atempfile.mkdtemp()sandbox, and merges neighbouring files in pairwise passes, the earlier run winning ties so the result stays stable. - Top k. Quickselect returns the top k by score (ties broken by start, user, then id), in order.
- Sweeps. Report the peak concurrency (ends before starts at equal times) and the merged busy periods.
- Inversion distance. Count the pairs that two orderings disagree on, by merge sort.
Demo the engine on six workloads: a small printed log, 20,000 events, an over-budget log, the top 5, the sweeps (including two touching events), and the distance between the score order and the start order. Then fuzz every output against sorted()-based or brute-force oracles, counting exceptions as failures. Show that an engine running its passes first key first is caught, with one wrong result printed. State the complexity of every part.
Stuck? Solve it with a mentor.
Your first 1-on-1 session is free.