Sub topic 15
Finding the k-th element by binary descent
This chapter assumes you have read the Fenwick tree chapters and are comfortable with i & -i, prefix queries, and point updates.
The problem
Suppose a Fenwick tree stores counts. Position i holds how many times the value i has been inserted. The k-th smallest inserted element is then the smallest index i whose prefix sum is at least k.
You could binary search over i and call prefix(i) at each step. That costs O(log n) steps with an O(log n) query each, so O(log² n) in total. Binary descent finds the same index in O(log n).
Why descent works
Cell t[pos + step] covers the step positions right after pos, provided pos is a multiple of 2 * step. Descent builds on that fact.
Start with pos = 0 and try powers of two from the largest down to 1. At each step, look at t[pos + step]:
- If it is less than
k, the answer lies beyond that block. Moveposforward and subtract the block's sum fromk. - Otherwise, the answer lies inside the block. Keep
posand try a smaller step.
Because the steps shrink and only add bits that are not yet set in pos, each probe lands on a cell that covers exactly the range you need. This is why no prefix call is needed. At the end, pos is the largest index whose prefix sum is less than k, so the answer is pos + 1.
Code
class Fenwick:
# 1-indexed Fenwick tree for prefix sums.
def __init__(self, n):
self.n = n
self.t = [0] * (n + 1)
def add(self, i, delta):
while i <= self.n:
self.t[i] += delta
i += i & -i
def prefix(self, i):
s = 0
while i > 0:
s += self.t[i]
i -= i & -i
return s
def find_kth(f, k):
# Smallest index i with prefix(i) >= k. Requires non-negative values and f.n >= 1.
# Returns f.n + 1 if k exceeds the total.
pos = 0
step = 1 << (f.n.bit_length() - 1)
while step:
nxt = pos + step
if nxt <= f.n and f.t[nxt] < k:
pos = nxt
k -= f.t[nxt]
step >>= 1
return pos + 1
f = Fenwick(5)
for idx, x in enumerate([1, 0, 2, 0, 1], start=1):
f.add(idx, x)
print(find_kth(f, 1)) # 1
print(find_kth(f, 2)) # 3
print(find_kth(f, 4)) # 5The starting step is the largest power of two not above n. The check nxt <= f.n stops the walk from reading past the array when n is not a power of two.
Tracing k = 4
The counts are [1, 0, 2, 0, 1], so the cells are t[4] = 3 and t[5] = 1.
Things to watch
- All values must be non-negative. The test
t[nxt] < krelies on prefix sums never decreasing. With negative values the descent can go wrong. - A
klarger than the total returnsn + 1. Check for this ifkcan be out of range. - Choose the starting step with
bit_length, not by looping overn. Forn = 5,n.bit_length()is 3, which gives a step of 4. - The Fenwick tree must be 1-indexed. Zero-indexed data needs a shift of one before it goes in, and the result needs a shift back.
Exercise
A Fenwick tree of size 4 holds the counts [0, 3, 0, 2]. What does find_kth(f, 3) return, and which cells does the descent probe?
Show answer
It returns 2. The cells are t[1] = 0, t[2] = 3, t[3] = 0, t[4] = 5. The first step is 4, and t[4] = 5 is not less than 3, so pos stays 0. Step 2 probes t[2] = 3, which is not less than 3, so pos stays 0. Step 1 probes t[1] = 0, which is less than 3, so pos becomes 1 and k stays 3. The result is pos + 1 = 2. The prefix sums are 0, 3, 3, 5, and index 2 is the first with a prefix sum of at least 3.