Sub topic 17
Common pitfalls: indexing, array size, and overflow
This chapter assumes you have read the earlier chapters and can write the recursive segment tree, the iterative segment tree, and the Fenwick tree. Most bugs in these structures come from a few boundary mistakes rather than from the algorithms.
Indexing conventions
The structures in this tutorial use three different conventions.
| Structure | Element indices | Query bounds |
|---|---|---|
| Recursive segment tree | 0-based | inclusive `[l, r]` |
| Iterative segment tree | 0-based | half-open `[l, r)` |
| Fenwick tree | 1-based | inclusive `[l, r]` |
Passing (1, 3) to the iterative tree when you meant "positions 1 to 3" silently drops position 3. Pick one convention for your own code and convert at the boundary.
The Fenwick tree has a worse failure. add(0, x) never terminates, because 0 & -0 is 0, so i never grows. The query range_sum(0, r) calls prefix(-1), which returns 0 without error and gives a wrong answer. A wrapper with a zero-based interface and bounds checks avoids both problems:
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
class ZeroBasedFenwick:
# Zero-based, inclusive API on top of the 1-indexed tree.
def __init__(self, n):
self.n = n
self.f = Fenwick(n)
def _check(self, i):
if not 0 <= i < self.n:
raise IndexError(f"index {i} outside 0..{self.n - 1}")
def add(self, i, delta):
self._check(i)
self.f.add(i + 1, delta)
def range_sum(self, l, r):
self._check(l)
self._check(r)
return self.f.prefix(r + 1) - self.f.prefix(l)
z = ZeroBasedFenwick(5)
for i, x in enumerate([5, 2, 7, 1, 3]):
z.add(i, x)
print(z.range_sum(1, 3)) # 10
try:
z.add(5, 1)
except IndexError as e:
print(e) # index 5 outside 0..4Array size
- The recursive segment tree needs
4 * nslots. A size of2 * nfails for somen, because the tree is not perfectly balanced and node numbers can exceed2n. - The iterative tree uses exactly
2 * nslots. - The Fenwick tree uses
n + 1slots, because slot 0 is unused.
An off-by-one in size usually shows up as an IndexError on only some inputs, so test with n = 1, n = 2, and sizes that are not powers of two.
Identity values and lazy tags
An out-of-range recursive query must return the identity of the operation. That is 0 for sums, positive infinity for minimum, and negative infinity for maximum. Returning 0 from a minimum tree gives wrong answers whenever all values are positive.
In a lazy tree, call _push before you descend into the children, in both add and query. If you skip it in query, reads see stale children.
Overflow
Python integers never overflow, but C++, Java, and Go integers do. Suppose 32-bit values are summed:
def wrap32(x):
# Simulates signed 32-bit wraparound.
return (x + 2**31) % 2**32 - 2**31
print(wrap32(10**9 * 3)) # -1294967296Use 64-bit sums even when the inputs fit in 32 bits. Watch for products too. The lazy update multiplies v * (hi - lo + 1), and the two-tree range Fenwick computes prefix * i. Both can exceed the range of the element type well before the final answer does.
Exercise
A recursive segment tree over n = 5 elements is allocated with 2 * n = 10 slots. Why is this unsafe, and what size should you use?
Show answer
The tree is not perfectly balanced, so node numbers (children at 2node and 2node+1) can go past 2n. For n = 5, a leaf can have node number 11 or higher, which is out of range for a size-10 list. Allocate 4 * n slots.