Sub topic 5
Turning Counts into Positions with Prefix Sums
This chapter assumes you have read the earlier chapters on the histogram version of counting sort and on sort stability. You should also be comfortable with Python lists and loops, and with reading O(n + k) style cost statements.
The histogram version of counting sort has a blind spot. It knows how many times each value appears, but it rebuilds the output by writing each value back count times. It never moves the original elements. That works for bare integers. It fails once each key has data attached, such as a name, an ID, or a whole database row, because the histogram has no record of which element produced which count.
The fix is to change the question the count array answers. "How many elements have key v?" becomes "where in the output does the first element with key v go?" A prefix sum over the counts answers that second question.
From counts to slot ranges
In sorted output, every element with key 0 comes first, then every element with key 1, and so on. So the elements with key v start right after all elements with smaller keys. The starting index for key v is therefore the number of elements whose key is less than v:
- start[v] = counts[0] + counts[1] + ... + counts[v − 1]
This is the exclusive prefix sum of the count array. "Exclusive" means the sum for position v leaves out counts[v] itself. The inclusive prefix sum includes it, so it gives the index just past the last slot for key v:
- end[v] = counts[0] + ... + counts[v] = start[v] + counts[v]
Together they give each key a half-open range of output indices, [start[v], end[v]). These ranges are laid end to end, they never overlap, and together they cover indices 0 to n − 1 exactly.
A worked example
Take the input [3, 1, 4, 1, 5, 2, 0] with keys in the range 0..5.
| key v | counts[v] | start[v] (exclusive) | end[v] (inclusive) | output slots |
|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 0 |
| 1 | 2 | 1 | 3 | 1, 2 |
| 2 | 1 | 3 | 4 | 3 |
| 3 | 1 | 4 | 5 | 4 |
| 4 | 1 | 5 | 6 | 5 |
| 5 | 1 | 6 | 7 | 6 |
Key 1 appears twice, so it gets a two-slot range, indices 1 and 2. A key that never appears would get an empty range where start equals end. The last end value, 7, equals n, the input length. That makes a quick sanity check.
Computing the prefix sums
The exclusive version needs care with ordering. You have to record the running total before you add the current count to it.
def exclusive_prefix_sums(counts):
"""Return (starts, total) where starts[v] = sum(counts[:v])."""
starts = [0] * len(counts)
total = 0
for v, c in enumerate(counts):
starts[v] = total # record before adding: this is what makes it exclusive
total += c
return starts, total
counts = [1, 2, 1, 1, 1, 1]
starts, total = exclusive_prefix_sums(counts)
print(starts, total) # [0, 1, 3, 4, 5, 6] 7The standard library can do the same thing. itertools.accumulate with initial=0 (Python 3.8 and later) returns k + 2 values: the k + 1 starts followed by the grand total.
from itertools import accumulate
counts = [1, 2, 1, 1, 1, 1]
running = list(accumulate(counts, initial=0))
starts, total = running[:-1], running[-1]
print(starts, total) # [0, 1, 3, 4, 5, 6] 7
inclusive = list(accumulate(counts))
print(inclusive) # [1, 3, 4, 5, 6, 7]Both versions take O(k) time, one step per possible key. That cost does not depend on n, which matters later when k is large compared with n.
Placing elements: the forward pass with start positions
With start positions available, placement is one more pass over the input. Each element goes to the current start slot for its key, and then that slot pointer moves forward by one so the next element with the same key lands just after it.
def exclusive_prefix_sums(counts):
starts = [0] * len(counts)
total = 0
for v, c in enumerate(counts):
starts[v] = total
total += c
return starts, total
def place_by_starts(a, k):
"""Sort non-negative integers in 0..k by placing each one at its position."""
counts = [0] * (k + 1)
for x in a:
counts[x] += 1
starts, total = exclusive_prefix_sums(counts)
assert total == len(a)
out = [None] * len(a)
for x in a: # forward pass, in input order
out[starts[x]] = x
starts[x] += 1 # next element with this key goes one slot later
return out
print(place_by_starts([3, 1, 4, 1, 5, 2, 0], 5)) # [0, 1, 1, 2, 3, 4, 5]Here is the placement pass traced on the example, starting from starts = [0, 1, 3, 4, 5, 6]:
| step | element x | writes out[i] | starts[x] after |
|---|---|---|---|
| 1 | 3 | out[4] = 3 | 5 |
| 2 | 1 | out[1] = 1 | 2 |
| 3 | 4 | out[5] = 4 | 6 |
| 4 | 1 | out[2] = 1 | 3 |
| 5 | 5 | out[6] = 5 | 7 |
| 6 | 2 | out[3] = 2 | 4 |
| 7 | 0 | out[0] = 0 | 1 |
Look at the two 1s. The first one in the input (step 2) went to index 1, and the second (step 4) went to index 2. Equal keys keep their input order. That is stability, and it comes from two choices together: start positions, and a forward pass. The next chapter turns this into a full sort for records and argues the stability property carefully.
When the pass finishes, each starts[v] has moved forward by exactly counts[v], so it now holds end[v]. After the loop, starts equals the inclusive prefix sums [1, 3, 4, 5, 6, 7]. You can assert this while debugging, and it catches most off-by-one mistakes.
The alternative: backward pass with end positions
Many textbooks, including CLRS, use the inclusive prefix sums together with a backward pass. Each end position points one past the last free slot for its key, so you decrement first and then write.
def place_by_ends(a, k):
"""Same result as place_by_starts, using inclusive sums and a backward pass."""
counts = [0] * (k + 1)
for x in a:
counts[x] += 1
for v in range(1, k + 1): # in-place inclusive prefix sums
counts[v] += counts[v - 1]
out = [None] * len(a)
for x in reversed(a): # backward pass fills each range from its end
counts[x] -= 1
out[counts[x]] = x
return out
print(place_by_ends([3, 1, 4, 1, 5, 2, 0], 5)) # [0, 1, 1, 2, 3, 4, 5]This version is also stable. The last element with key v in the input is visited first and takes the last slot of v's range. Earlier elements fill in toward the front. The two pairings to remember:
| prefix sum | pass direction | pointer update | stable? |
|---|---|---|---|
| exclusive (starts) | forward | write, then increment | yes |
| inclusive (ends) | backward | decrement, then write | yes |
| inclusive (ends) | forward | decrement, then write | no, equal keys come out reversed |
| exclusive (starts) | backward | write, then increment | no, equal keys come out reversed |
The two stable combinations do the same amount of work. The forward-and-starts version reads the input in memory order, which tends to be a little friendlier to hardware prefetching. The backward-and-ends version computes its prefix sums in place with a simpler loop. Pick one and use it consistently.
Common errors and edge cases
- Mixing the pairings. A forward pass with end positions still sorts by key, but equal keys come out in reverse order. A test with only bare integers will never show this, because equal integers look identical. Test with records that carry a tag.
- Forgetting to update the pointer. If you skip
starts[x] += 1, every element with the same key writes to the same slot. Later writes overwrite earlier ones, andNonevalues are left in the output. - Recording after adding. If the exclusive loop does
total += cbeforestarts[v] = total, you get inclusive sums under an exclusive name. A forward pass then writes one slot too far right, and the largest key raisesIndexError. - Key range too small. Keys must lie in 0..k. A key of k + 1 raises
IndexErrorin the counting pass. A negative key is worse in Python, becausecounts[-1]silently increments the last bucket. Check the bounds at the input boundary if the data is untrusted. - Empty input and empty buckets. Both work without special cases. An absent key gets a zero-width range, and its pointer is never used.
- Reusing the count array. Both placement passes modify the position array. If you need the original counts later, copy them first.
Exercises
Exercise
The count array for keys 0..3 is [2, 0, 3, 1]. Give the exclusive prefix sums, the inclusive prefix sums, and the output slots assigned to key 2. What range does key 1 get?
Show answer
Exclusive: [0, 2, 2, 5]. Inclusive: [2, 2, 5, 6]. Key 2 gets slots [2, 5), meaning indices 2, 3, and 4. Key 1 gets the empty range [2, 2) because it never appears. The final inclusive value, 6, equals n.
Exercise
Someone changes placebyends to loop for x in a: instead of for x in reversed(a): and keeps everything else. They sort [("p", 1), ("q", 1)] by the second field. What order comes out, and why?
Show answer
The output is [("q", 1), ("p", 1)]. Key 1 has end position 2. The forward pass visits ("p", 1) first, decrements the pointer to 1, and writes it to index 1. Then ("q", 1) is written to index 0. Filling a range from the back while reading the input from the front reverses equal keys, so the sort is not stable.
Exercise
After the forward placement pass in placebystarts, what does the starts array contain, and how can you use that as a check?
Show answer
Each starts[v] has been incremented counts[v] times, so it equals the inclusive prefix sum end[v]. In particular starts[k] equals len(a). If you assert that starts matches list(accumulate(counts)) after the pass, you catch skipped increments and off-by-one prefix sums.