Sub topic 7
Handling Duplicates With Three-Way Partitioning
This chapter assumes you have read the earlier chapters on Lomuto partitioning, the in-place iterative quickselect, and the expected-time analysis. You should be comfortable reading loop invariants written as slice ranges such as a[lo:lt], and you should know why a random pivot gives expected O(n) time on inputs with distinct values.
Every argument so far has quietly assumed that the values are mostly distinct. Real data often is not. Ratings from 1 to 5, HTTP status codes, ages in years, and boolean flags all contain huge numbers of repeated values. Standard two-way quickselect handles repeated values badly. This chapter shows how badly, explains the cause, and replaces the partition step with one that groups equal values together.
The Problem: Equal Keys All Land on One Side
Recall the Lomuto partition. It moves every element that is strictly less than the pivot to the left, and everything else ends up on the right. An element equal to the pivot counts as "everything else."
Consider an array where every value is the same, for example 2,000 copies of 7. Here is what one Lomuto pass does:
- A random index is chosen, but every candidate pivot is
7. - No element satisfies
a[i] < 7, sostorenever moves fromlo. - The pivot is swapped into position
lo, and the function returnslo.
The pivot lands at the far left of the range every time. If k is larger than lo, the loop sets lo = p + 1 and the range shrinks by exactly one element. Each pass still scans the whole remaining range, so the total work is (n-1) + (n-2) + ... + 1, which is about n²/2.
Randomization does not help here. A random pivot protects you against bad orderings of the input. It cannot protect you when every possible pivot has the same value, because every choice produces the same lopsided split. The same failure appears, to a lesser degree, whenever a few values dominate the array.
Measuring the Damage
The code below counts element examinations in the Lomuto-based quickselect and in a three-way version on an array of 2,000 equal values. Both functions count one unit each time the partition loop looks at an element.
import random
def lomuto_partition(a, lo, hi, p, counter):
a[p], a[hi] = a[hi], a[p]
pivot = a[hi]
store = lo
for i in range(lo, hi):
counter[0] += 1
if a[i] < pivot:
a[store], a[i] = a[i], a[store]
store += 1
a[store], a[hi] = a[hi], a[store]
return store
def quickselect_lomuto(a, k, counter):
lo, hi = 0, len(a) - 1
while True:
if lo == hi:
return a[lo]
p = lomuto_partition(a, lo, hi, random.randint(lo, hi), counter)
if k == p:
return a[k]
elif k < p:
hi = p - 1
else:
lo = p + 1
def quickselect3_counted(a, k, counter):
lo, hi = 0, len(a) - 1
while lo < hi:
pivot = a[random.randint(lo, hi)]
lt, i, gt = lo, lo, hi
while i <= gt:
counter[0] += 1
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
if k < lt:
hi = lt - 1
elif k > gt:
lo = gt + 1
else:
return a[k]
return a[k]
n = 2000
data = [7] * n
c1 = [0]
print(quickselect_lomuto(list(data), n - 1, c1), c1[0]) # 7 1999000
c2 = [0]
print(quickselect3_counted(list(data), n - 1, c2), c2[0]) # 7 2000Both counts are deterministic, because every pivot choice is equivalent. Lomuto examines 1,999,000 elements. The three-way version examines 2,000 and finishes in a single pass. Doubling n roughly quadruples the first number and only doubles the second.
The Three-Way Partition and Its Invariant
Three-way partitioning, also called the Dutch national flag algorithm after Edsger Dijkstra's original framing, divides the range a[lo..hi] into three groups: less than the pivot, equal to it, and greater than it. It does this in one left-to-right pass with three indices:
ltmarks the first element of the equal region.iis the element currently being examined.gtmarks the last element of the unexamined region.
At the top of every loop iteration, these four regions hold:
| Slice | Contents |
|---|---|
| `a[lo:lt]` | strictly less than `pivot` |
| `a[lt:i]` | equal to `pivot` |
| `a[i:gt+1]` | not yet examined |
| `a[gt+1:hi+1]` | strictly greater than `pivot` |
At the start, lt = i = lo and gt = hi, so the first, second, and fourth regions are empty and everything is unexamined. Each iteration shrinks the unexamined region by one element. The loop ends when i > gt, because then that region is empty.
The three cases keep the invariant true for different reasons:
- Less than the pivot. Swapping
a[i]witha[lt]puts the small value at the end of the "less" region. The element moved to positionicame froma[lt], which was the first element of the equal region. It is therefore equal to the pivot, or, if the equal region was empty, it is the small value itself. Either way, bothltandican advance safely. - Greater than the pivot. Swapping
a[i]witha[gt]puts the large value at the start of the "greater" region. The element that arrives at positionicame from the unexamined region, so nothing is known about it yet. That is whyidoes not advance: the next iteration must examine the new arrival. - Equal to the pivot. The element already sits just past the equal region, so advancing
iextends that region.
Tracing an Example
Take a = [5, 5, 5, 1, 5, 9, 5], k = 3, and suppose the random pivot value is 5.
| Step | `a[i]` | Action | Array after | `lt` | `i` | `gt` |
|---|---|---|---|---|---|---|
| start | `[5,5,5,1,5,9,5]` | 0 | 0 | 6 | ||
| 1 | 5 | equal, `i += 1` | `[5,5,5,1,5,9,5]` | 0 | 1 | 6 |
| 2 | 5 | equal, `i += 1` | `[5,5,5,1,5,9,5]` | 0 | 2 | 6 |
| 3 | 5 | equal, `i += 1` | `[5,5,5,1,5,9,5]` | 0 | 3 | 6 |
| 4 | 1 | less, swap with `a[0]` | `[1,5,5,5,5,9,5]` | 1 | 4 | 6 |
| 5 | 5 | equal, `i += 1` | `[1,5,5,5,5,9,5]` | 1 | 5 | 6 |
| 6 | 9 | greater, swap with `a[6]` | `[1,5,5,5,5,5,9]` | 1 | 5 | 5 |
| 7 | 5 | equal, `i += 1` | `[1,5,5,5,5,5,9]` | 1 | 6 | 5 |
Now i > gt, so the pass ends with lt = 1 and gt = 5. The equal block is a[1..5]. Since 1 <= 3 <= 5, the answer is a[3] = 5, and no further passes are needed. In step 6 the value 5 that was swapped in from the right end gets examined in step 7 because i did not move.
The Selection Step
After partitioning, every index in lt..gt holds the pivot value, and those indices are exactly the positions the pivot value would occupy in sorted order. That gives three outcomes:
k < lt: the answer is in the "less" region, so sethi = lt - 1.k > gt: the answer is in the "greater" region, so setlo = gt + 1.- otherwise:
a[k]equals the pivot and is the answer.
The full in-place function from the topic plan follows directly:
import random
def quickselect3(a, k):
"""In-place quickselect with three-way (Dutch national flag) partitioning."""
if not 0 <= k < len(a):
raise IndexError("k out of range")
lo, hi = 0, len(a) - 1
while lo < hi:
pivot = a[random.randint(lo, hi)]
lt, i, gt = lo, lo, hi
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
# Now a[lo:lt] < pivot, a[lt:gt+1] == pivot, a[gt+1:hi+1] > pivot
if k < lt:
hi = lt - 1
elif k > gt:
lo = gt + 1
else:
return a[k]
return a[k]
print(quickselect3([5, 5, 5, 1, 5, 9, 5], 3)) # 5
print(quickselect3([3, 1, 2], 0)) # 1
print(quickselect3([4, 4, 4, 4], 2)) # 4The outer loop runs while lo < hi. When the range shrinks to one element, that element must be the answer, so the final return a[k] handles it. Every pass removes at least the pivot's equal block, which always has at least one element, so the loop always terminates.
Why This Restores Expected Linear Time
The expected-time argument from the analysis chapter depended on the pivot landing somewhere in the middle half of the range with reasonable probability. With two-way partitioning, duplicates break that argument because many equal values can share one rank position on the wrong side.
With three-way partitioning, duplicates can only help. Picking a random element picks a value with probability proportional to how often it appears. The equal block for that value is discarded in full, and the remaining range is everything on one side of it. Heavily repeated values are both more likely to be picked and remove more elements when picked. The worst case for random pivots is still all distinct values, which is exactly the case the earlier analysis already covered. So expected time stays O(n) for every input, including inputs with many duplicates.
The worst case is still O(n²) with unlucky pivots on distinct values. Three-way partitioning fixes the duplicate problem and nothing else. The later chapters on median of medians and introselect deal with the worst case.
Costs and Alternatives
Three-way partitioning is not free. Each element may need two comparisons (< and then >), and every element greater than the pivot costs a swap. Lomuto only swaps elements smaller than the pivot. On data with all distinct values, the three-way version does more work per pass for no benefit.
| Partition scheme | All-equal input | Distinct input | Notes |
|---|---|---|---|
| Lomuto, strict `<` | O(n²) | expected O(n) | simplest; fails on duplicates |
| Hoare, stop on equal | expected O(n) | expected O(n) | splits equal runs near the middle; fewer swaps on distinct data, but swaps equal pairs needlessly |
| Dijkstra three-way | O(n), one pass | expected O(n) | removes the equal block; up to 2 comparisons per element |
| Bentley–McIlroy three-way | O(n), one pass | expected O(n) | keeps equal keys at the ends during the scan and moves them to the middle afterward; overhead close to Hoare when duplicates are rare |
Hoare's original scheme also avoids the quadratic case, because both scanning pointers stop on elements equal to the pivot. Equal runs then get split roughly in half rather than pushed to one side. It does not discard the equal block, however, so it keeps partitioning ranges full of equal values that three-way partitioning would finish in one pass. Production libraries usually pick Hoare-style or Bentley–McIlroy partitioning for speed. Dijkstra's version is the easiest to get right and to reason about, which is why it is the version shown here.
Common Mistakes
- Advancing
iafter the "greater" swap. The element swapped in froma[gt]has not been examined. Skipping it can leave a large value inside the "less" or "equal" region. - Looping with
i < gt. The element atgtitself is still unexamined, so the condition must bei <= gt. - Reading the pivot by index during the loop. Use
pivot = a[r]once before the loop, as a value. Swaps move elements around, soa[r]may hold a different value later. - Wrong bounds after the pass. The equal block is
lt..gtinclusive. Usinghi = ltorlo = gtleaves a pivot-equal element in the next range. That is still correct, but it wastes work. Writinghi = lt - 2or something similar skips real candidates. - Assuming the input is untouched. Like the other in-place versions,
quickselect3reorders its argument. Passlist(a)if the caller needs the original order.
Exercises
Exercise
In the trace above, suppose the random pivot value had been 1 instead of 5. Give lt and gt after the partition pass and say what happens next for k = 3.
Show answer
Only one element equals 1, and none is smaller, so after the pass a[0] = 1, lt = 0 and gt = 0, and the other six elements (the five 5s and the 9) are in the "greater" region. Since k = 3 > gt, the loop sets lo = 1 and partitions a[1..6] again. Any pivot chosen from that range (5 or 9) finishes the job: a pivot of 5 gives an equal block covering positions 1..5, which contains k = 3, and a pivot of 9 shrinks the range to the 5s, which the next pass resolves.
Exercise
A student changes the "greater" branch to swap a[i] with a[gt], then do both gt -= 1 and i += 1. Give a small input that makes the modified function return a wrong answer.
Show answer
Use a = [3, 1, 2] with k = 0, and suppose the pivot value is 2. At i = 0, a[0] = 3 > 2, so it swaps with a[2], giving [2, 1, 3], gt = 1, and then the bug sets i = 1. The 2 now at index 0 is never examined. At i = 1, a[1] = 1 < 2, so it swaps with a[lt = 0], giving [1, 2, 3], lt = 1, i = 2. The loop ends with lt = 1 and gt = 1. Here k = 0 < lt, so the function searches a[0..0] and returns 1, which happens to be right. Now try k = 1 with pivot 2 on a = [3, 2, 1]. At i = 0, 3 > 2, so it swaps with a[2], giving [1, 2, 3], gt = 1, and the bug sets i = 1. The 1 at index 0 is skipped. a[1] = 2 is equal, so i = 2 and the loop ends with lt = 0 and gt = 1. The function treats positions 0..1 as the equal block, and for k = 0 it returns a[0] = 1. That result is only luck: the invariant claims a[0] equals 2, which is false. With a = [3, 2, 1], pivot 2, and the bug, the "equal" block contains 1, so any later step that relies on lt..gt holding the pivot value is wrong. For example, the function returns the claimed pivot position without checking it. Fix the bug by leaving i unchanged in the "greater" branch.
Exercise
An array holds one million exam grades, each an integer from 0 to 100. Compare how many partition passes Lomuto quickselect and three-way quickselect need, roughly, to find the median.
Show answer
With Lomuto, each of the 101 values appears about 10,000 times. Once the range narrows to elements equal to the median value, each pass removes only one element, so it can take thousands of passes over shrinking ranges of up to about 10,000 elements, which is tens of millions of examinations. With three-way partitioning, each pass discards an entire value group, and at most 101 distinct values exist. Random pivots narrow the range of values roughly geometrically, so it finishes in a handful of passes (about log2(101), or 7, on average) with total work a small multiple of one million.