Sub topic 1
What It Means to Find the k-th Smallest Element
Many everyday questions are selection questions. You might want the median response time from a server log, the 95th-percentile latency, the cheapest three flights, or the score that separates the top 10% of students. None of these needs the whole list in order. Each needs one element: the one that would sit at a particular position if the list were sorted.
This chapter defines that problem precisely, so the later chapters on quickselect have a fixed target to aim at.
Prerequisites
This chapter assumes you are comfortable with the following:
- Basic Python syntax: functions, loops, lists, and slicing.
- Arrays and zero-based indexing.
- Big-O notation, at least for O(n), O(n log n), and O(n^2).
- Recursion. Later chapters rely on it, though this chapter does not.
- Quicksort, which helps but is not required.
The Selection Problem
The selection problem is: given a collection of n comparable items and an integer k, return the item that would be at position k if the collection were sorted in ascending order. That item is the k-th order statistic.
Some order statistics have familiar names:
| Name | Zero-based k | One-based k |
|---|---|---|
| Minimum | 0 | 1 |
| Maximum | n - 1 | n |
| Median (odd n) | (n - 1) // 2 | (n + 1) // 2 |
| Lower median (even n) | (n - 1) // 2 | n // 2 |
| Upper median (even n) | n // 2 | n // 2 + 1 |
The definition only describes what the answer is. It says nothing about how to compute it, so the result does not depend on the method you use. Sorting, a heap, and quickselect must all return the same element.
A Reference Implementation
The definition translates directly into code: sort a copy and index into it. This version takes O(n log n) time, and the rest of the tutorial works on doing better. It is still useful as a reference implementation, a slow but obviously correct version you can test faster code against.
def kth_smallest_reference(items, k):
"""Return the k-th smallest element (0-based) by sorting a copy."""
if not 0 <= k < len(items):
raise IndexError(f"k={k} out of range for {len(items)} items")
return sorted(items)[k]
data = [9, 1, 8, 2, 7, 3]
print(kth_smallest_reference(data, 0)) # 1, the minimum
print(kth_smallest_reference(data, 2)) # 3
print(kth_smallest_reference(data, len(data) - 1)) # 9, the maximum
print(data) # [9, 1, 8, 2, 7, 3], unchangedThe function works on a copy, so the caller's list stays the same. Keep this in mind for later chapters. The in-place quickselect implementations reorder the input, and library routines such as std::nth_element also rearrange the range they are given.
Zero-Based Versus One-Based k
People usually say "the 3rd smallest" and mean one-based counting. Python, C++, and NumPy index from zero. Code that mixes the two produces off-by-one bugs, which are the most common error in selection code.
This tutorial always uses zero-based k. Convert at the boundary of your program, not inside the algorithm:
def nth_smallest_one_based(items, n):
"""Human-facing wrapper: n = 1 means the minimum."""
return kth_smallest_reference(items, n - 1)
print(nth_smallest_one_based([9, 1, 8, 2, 7, 3], 3)) # 3Duplicates Count as Separate Positions
Order statistics count positions, not distinct values. In [4, 2, 4, 1] the sorted view is [1, 2, 4, 4], so k = 2 and k = 3 both return 4. If you want the k-th smallest distinct value, that is a different problem. Deduplicate first, for example with sorted(set(items))[k].
Duplicates also matter for performance. Chapter 7 shows how many equal keys can make a naive quickselect slow down, and how three-way partitioning fixes that.
Common Errors
- Off by one. Passing a one-based rank to a zero-based function returns the next larger element and gives no error.
- Out-of-range k. Valid zero-based values run from 0 to n - 1. An empty list has no order statistics at all. Raise an error instead of returning a sentinel such as
None. - Ambiguous median. For even n there are two middle elements. Choose the lower or upper median on purpose, or average them if your domain calls for it. Averaging is not a selection result.
- Assuming the input is preserved. In-place selection routines reorder their input. Copy the input first if the original order matters.
Exercise
For the list [12, 5, 7, 5, 20, 1], give the zero-based k and the returned value for (a) the 2nd smallest element, (b) the lower median, and (c) the 2nd largest element.
Show answer
The sorted view is [1, 5, 5, 7, 12, 20] and n = 6. (a) The 2nd smallest is one-based rank 2, so zero-based k = 1, which returns 5. (b) The lower median is at k = (6 - 1) // 2 = 2, which returns 5. The duplicate 5 occupies both index 1 and index 2. (c) The 2nd largest is zero-based largest-rank 1, so k = n - 1 - 1 = 4, which returns 12.
Exercise
Why is kthsmallestreference still worth keeping once you have a faster quickselect?
Show answer
Its correctness follows directly from the definition. That makes it a good test oracle: run both functions on many random lists and values of k, and check that they always agree.