Iterative segment trees are faster in practice (no recursion overhead) and use exactly space:
class IterativeSegTree:
def __init__(self, arr):
self.n = len(arr)
self.tree = [0] * (2 * self.n)
# Build: leaves at positions n to 2n-1
for i in range(self.n):
self.tree[self.n + i] = arr[i]
for i in range(self.n - 1, 0, -1):
self.tree[i] = self.tree[2*i] + self.tree[2*i+1]
Leaves are stored in positions to . Internal nodes in positions to . Position is unused.
This layout is more cache-friendly and avoids the space overhead.