Segment Tree Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Segment Tree runs in O(log n) time and O(n) space, in Python as in every other language.
- ✓A plain list is the storage; there is no tree type to import. Python's int is arbitrary precision, so a sum segment tree over any input simply cannot overflow, the single largest source of subtle bugs in this data structure does not exist here.
- ✓Build the tree iteratively, bottom-up, into a list of size 2n: leaves occupy indices n..2n-1 and every internal node i is merge(tree[2i], tree[2i+1]).
- ✓The Python trap: The recursive textbook implementation is roughly an order of magnitude slower in CPython than the iterative one, because each of the O(log n) levels costs a full Python frame push.
- ✓A list of Python ints is an array of pointers to heap-allocated objects, so every access is an indirection and the tree is not cache-friendly at all.
What Segment Tree actually is
Segment Tree in Python: what you actually reach for
Python implementation
class SegmentTree:
"""Iterative, bottom-up. Python ints are arbitrary precision:
a sum tree here CANNOT overflow."""
def __init__(self, data: list[int]) -> None:
self._n = len(data)
self._tree = [0] * (2 * self._n)
self._tree[self._n:] = data
for i in range(self._n - 1, 0, -1):
self._tree[i] = self._tree[2 * i] + self._tree[2 * i + 1]
def update(self, index: int, value: int) -> None:
i = index + self._n
self._tree[i] = value
while i > 1:
i //= 2
self._tree[i] = self._tree[2 * i] + self._tree[2 * i + 1]
def query(self, left: int, right: int) -> int:
"""Sum of [left, right)."""
total = 0
lo, hi = left + self._n, right + self._n
while lo < hi:
if lo & 1:
total += self._tree[lo]
lo += 1
if hi & 1:
hi -= 1
total += self._tree[hi]
lo //= 2
hi //= 2
return totalThink Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Segment Tree?
A plain list is the storage; there is no tree type to import. Python's int is arbitrary precision, so a sum segment tree over any input simply cannot overflow, the single largest source of subtle bugs in this data structure does not exist here. For static range minimum queries, functools.reduce with min over a slice is the naive baseline the tree is beating.
What is the most common Python mistake when implementing Segment Tree?
The recursive textbook implementation is roughly an order of magnitude slower in CPython than the iterative one, because each of the O(log n) levels costs a full Python frame push. On a competitive-programming or high-volume workload that is the difference between passing and timing out, and profiling points at the language rather than the algorithm. Note the recursion depth itself is only log n, so sys.setrecursionlimit is not the issue people assume.
How does Segment Tree actually perform in Python?
A list of Python ints is an array of pointers to heap-allocated objects, so every access is an indirection and the tree is not cache-friendly at all. For large numeric workloads, array.array or a NumPy array cuts memory several-fold and improves locality dramatically. Arbitrary-precision arithmetic costs nothing extra while values stay small, CPython has a fast path for machine-word-sized ints. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.