Segment Tree
Notes and typical questions for Segment Tree related questions
Notes
Introduction: https://www.bilibili.com/video/BV1cb411t7AM/?share_source=copy_web&vd_source=28fd44c5c9b62466ed4422197e99ce77
Segment Tree Size — Why
4*nIs EnoughA segment tree is a binary tree built over an array of length
n.Leaves represent single elements; Parent nodes represent ranges.
If
nis not a power of 2, the tree is built as if the array length were the next power of twoL ≥ n.A full binary tree with
Lleaves has2*L − 1nodes.For any
n, the next power of two satisfiesL < 2*n.Therefore, total nodes:
≤ 2L − 1 < 2 * (2n) = 4nSo allocating an array of size
4 * nalways guarantees enough space.
If the problem asks “Find the smallest index > x".
Think:
TreeSet.higher(x)first. NOT range sum + binary searchEven if you want to use the segment tree, you must extend the template to support a “find first index in range satisfying a condition” operation, instead of doing binary search + multiple range queries—for example, LC 1488.
The node must store enough aggregate info to determine whether the current segment may contain a valid answer (e.g., sum/max/min).
During query, first check feasibility, then descend left-first to locate the smallest valid index.
This keeps each operation
O(logn)instead ofO(log²n).
Typical Questions
Max Segment Tree
LC 3477. Fruits Into Baskets II
Same as below.
TC: O(n+n∗((logn)2+logn))=>O(n∗logn)
SC: O(n)
🔴 TC 3479. Fruits Into Baskets III
TC: O(n+n∗((logn)2+logn))=>O(n∗logn)
SC: O(n)
Last updated