Module contents
Lesson 10 of 33Advanced 105 min

Range query data structures

Build a range-query toolkit: prefix sums, Fenwick and segment trees, lazy propagation, sparse tables, LCA and augmented trees.

After this lesson you can

  • Choose a range-query structure for the aggregate and updates required.
  • Implement a Fenwick tree and explain the arithmetic of i & (−i).
  • Design a lazy segment tree by identifying aggregate and update monoids.
  • Answer RMQ in O(1) with a sparse table and reduce LCA to RMQ.
  • Augment a balanced tree for order statistics and interval queries.

Before you start

Motivation: aggregates over changing intervals

A pattern appears whenever a program stores a sequence and someone asks about pieces of it: what is their sum or minimum, how many are there, where is the kk-th? If the sequence never changed, precomputation would suffice. If nobody asked, storing it would suffice. The hard part is supporting both at once.

  • Window metrics. An observability dashboard stores request counts and latency minute by minute. Questions ask for aggregates over arbitrary windows (“requests between 10:00 and 10:45”, “worst latency in the last hour”), while data keep arriving. If a histogram of latency buckets is also stored, the 99th percentile is “the bucket where the cumulative sum reaches 99% of the total”: a prefix sum to invert.
  • Cumulative frequencies in a compressor. Adaptive arithmetic coding assigns each symbol interval [F(s−1),F(s))[F(s-1), F(s)) of cumulative frequencies, then increments its frequency after encoding. Each symbol needs a prefix sum and point update, and the decoder performs the inverse search: which symbol has the cumulative frequency just read. This is exactly the problem Peter Fenwick solved in 1994.
  • Lines of code. An editor must translate “line 12,345” to a byte position and back. The starting position of line kk is the sum of the lengths of the preceding k−1k - 1 lines, and each keystroke changes one length. VS Code’s text buffer, rewritten in 2018, is a red-black tree of pieces in which each node stores the length and newline count of its left subtree: an augmented tree, the final protagonist of this lesson.

All three ask for an aggregate over an interval of a changing sequence. The answer is a ladder of structures, each buying something different: prefix sums (static, O(1)\bigO(1) per query), Fenwick tree (sums with updates, very short code), segment tree (any associative aggregate and range updates), sparse table (minima in O(1)\bigO(1) on fixed data), and augmented trees (keys inserted and deleted rather than fixed positions). Finally, the same idea leaves the array for the plane and space: quadtrees and octrees.

StructurePreprocessingQueryUpdateAggregates
Prefix sumsO(n)\bigO(n)O(1)\bigO(1)rebuild, O(n)\bigO(n)with inverse (groups): sum, XOR
Fenwick treeO(n)\bigO(n)O(log⁡n)\bigO(\log n)point, O(log⁡n)\bigO(\log n)inverse for ranges; prefixes of any commutative monoid
Segment treeO(n)\bigO(n)O(log⁡n)\bigO(\log n)point or range, O(log⁡n)\bigO(\log n)any monoid
Sparse tableO(nlog⁡n)\bigO(n \log n)O(1)\bigO(1)noneassociative and idempotent: min, max, gcd
Augmented treeO(nlog⁡n)\bigO(n \log n)O(log⁡n)\bigO(\log n)insert and delete keys, O(log⁡n)\bigO(\log n)anything computable from children

Prefix sums: the static case

Let a1,…,ana_1, \dots, a_n be a fixed sequence. Its prefix sums are

P0=0,Pi=Pi−1+ai=a1+⋯+ai,P_0 = 0, \qquad P_i = P_{i-1} + a_i = a_1 + \cdots + a_i,

and every interval sum is a subtraction: al+⋯+ar=Pr−Pl−1a_l + \cdots + a_r = P_r - P_{l-1}. Preprocessing with nn additions turns each query into two reads. In code, with zero-based indices and half-open ranges, the formula is even cleaner: the sum of a[l:r] is P[r] - P[l].

Subtraction is both the key and the limitation. It works because addition has an inverse: Pr=Pl−1+(al+⋯+ar)P_r = P_{l-1} + (a_l + \cdots + a_r) can be rearranged to obtain the part of interest. With minimum nothing can be isolated: if min⁡(a1,…,al−1)≤min⁡(a1,…,ar)\min(a_1, \dots, a_{l-1}) \le \min(a_1, \dots, a_r), the global minimum is already reached before ll, both prefixes have the same value and say nothing about the minimum of al,…,ara_l, \dots, a_r, which can be any value at least that large. Every aggregate forming a group (associative, with identity and inverses), such as addition, XOR or multiplication of nonzero numbers, admits prefix sums; those forming only a monoid, such as minimum, need other ideas.

Prefix sums are the scan operation you will see parallelized in lesson 26, and appear in disguise in many places: a histogram’s cumulative distribution function, roulette-wheel sampling from a discrete distribution (a prefix sum and binary search), or the forward step of CTC, accumulating probabilities along the sequence.

In two dimensions

For a matrix A∈Rn×m\mat{A} \in \R^{n \times m}, define Si,jS_{i,j} as the sum of the rectangle formed by the first ii rows and jj columns. By inclusion-exclusion,

Si,j=aij+Si−1,j+Si,j−1−Si−1,j−1,S_{i,j} = a_{ij} + S_{i-1,j} + S_{i,j-1} - S_{i-1,j-1},

and the sum of any rectangle with rows r0+1,…,r1r_0 + 1, \dots, r_1 and columns c0+1,…,c1c_0 + 1, \dots, c_1 is

Sr1,c1−Sr0,c1−Sr1,c0+Sr0,c0.S_{r_1, c_1} - S_{r_0, c_1} - S_{r_1, c_0} + S_{r_0, c_0}.

The two subtractions remove the top and left strips, and since their common corner was removed twice, it is added once. In computer vision this table is called an integral image (summed-area table, Crow, 1984): Viola and Jones’s face detector (2001) used it to evaluate thousands of rectangular features with four reads per rectangle regardless of size. In dd dimensions the formula has 2d2^d alternating-sign terms.

Differences: range updates over static data

The inverse problem is also common: many “add vv to al,…,ara_l, \dots, a_r” updates and one read at the end. The difference array Di=ai−ai−1D_i = a_i - a_{i-1} turns each range update into two point updates, Dl+=vD_l \mathrel{+}= v and Dr+1−=vD_{r+1} \mathrel{-}= v, because differences within the range do not change. A prefix sum of DD reconstructs aa. Difference and prefix sum are inverses, like derivative and integral, and combining them will be the key to range Fenwick trees. But once updates and queries are interleaved, both techniques cost O(n)\bigO(n) per operation on their bad side. A middle ground is needed.

The Fenwick tree

The idea is to store partial block sums, neither all prefix sums (expensive to update) nor individual elements (expensive to sum). Fenwick’s block choice is as economical as possible: one array the same size as the data, no pointers, with blocks read from the binary representation of the index.

Odd indices store one element; multiples of 2 that are not multiples of 4 store two; multiples of 4 that are not multiples of 8 store four; and so on. In the figure each tit_i is a horizontal block, placed in the row of its lowbit⁡\operatorname{lowbit}.

InteractiveBits of the Fenwick tree
Cada t[i] guarda la suma de su franja (i − lowbit(i), i]; la fila es su lowbit34t[2]49t[4]514t[6]231t[8]58t[10]521t[12]916t[14]980t[16]31000011200010430001114001005500101960011027001116801000590100131001010511010118120110091301101714011109150111131610000a[i]
Index chain in binary
13 = 01101 − 1 → 12
12 = 01100 − 4 → 8
8 = 01000 − 8 → 0 (done)
Two’s complement at the current step
i = 01000 (8)
−i = 11000 (~i + 1)
i&−i = 01000 (8)
  • band added
  • band at current step
step 3 / 3
t[8]t[8] covers (0,8](0, 8] and adds 31. Clear the lowest bit: 8−8=08 - 8 = 0, done.
Operation
13
Accumulator61
Direct sum a1+⋯+ara_1 + \dots + a_r61
Accesses to tt3
Set bits in rr3 (01101)
Each strip is a tit_i and covers (i−lowbit⁡(i),i](i - \operatorname{lowbit}(i), i]; the number on the right is its stored sum. In ‘Prefix sum’, visited strips tile (0,r](0, r] from right to left, and below each index is shown in binary with its lowest set bit underlined: each step removes it. Try r=13r = 13, then r=15r = 15 and r=16r = 16: how many steps in each case? In ‘Update’, the dashed vertical marks position pp and corrected strips are exactly those it crosses. In ‘k-th’, descending by powers of two finds the first index whose cumulative sum reaches kk with one access per level.

The lowest bit in two’s complement

In two’s complement, −i-i is calculated by inverting every bit and adding 1. If ii is written x 1 0kx\,1\,0^k (a prefix xx, the lowest set bit and kk zeros), then ∼i=xˉ 0 1k\sim i = \bar{x}\,0\,1^k and, on adding 1, the carry travels through the ones and stops at zero: −i=xˉ 1 0k-i = \bar{x}\,1\,0^k. Bitwise AND with ii clears the prefix (x∧xˉ=0x \wedge \bar{x} = 0), keeps bit kk and leaves zeros below:

i&(−i)=0⋯0 1 0k=lowbit⁡(i).i \mathbin{\&} (-i) = 0\cdots0\,1\,0^k = \operatorname{lowbit}(i).

With i=12=011002i = 12 = 01100_2: −12=101002-12 = 10100_2 in five bits, and 01100&10100=00100=401100 \mathbin{\&} 10100 = 00100 = 4. The interactive’s right panel performs this calculation at every step. Python integers have arbitrary precision but behave like two’s complement with infinitely many leading ones, so i & -i works the same way.

Query: remove the lowest set bit

Proof

Subtracting lowbit⁡(rj)\operatorname{lowbit}(r_j) clears the lowest set bit of rjr_j without touching the others, so each step reduces the number of set bits by one and the sequence ends at 00 after popcount⁡(r)\operatorname{popcount}(r) steps. The block of trjt_{r_j} is (rj−lowbit⁡(rj),rj]=(rj+1,rj](r_j - \operatorname{lowbit}(r_j), r_j] = (r_{j+1}, r_j]: consecutive blocks fit without gaps or overlap, from r0=rr_0 = r down to 00.

∎

With r=13=11012r = 13 = 1101_2: t13t_{13} covers (12,13](12, 13], t12t_{12} covers (8,12](8, 12] and t8t_8 covers (0,8](0, 8]. Three set bits, three summands. This is the binary representation of 13, 8+4+18 + 4 + 1, read from bottom to top.

Update: add the lowest set bit

Changing apa_p requires correcting every block containing pp. That there are few, and that adding the lowest set bit finds them, is the heart of the structure.

Proof

Let q=p−1q = p - 1. The block of jj, with lowbit⁡(j)=2k\operatorname{lowbit}(j) = 2^k, contains pp if and only if j−2k≤q<jj - 2^k \le q < j. Write j=H⋅2k+1+2kj = H\cdot 2^{k+1} + 2^k, where HH are the bits of jj above kk. Then j−2k=H⋅2k+1j - 2^k = H \cdot 2^{k+1} and the condition says q∈[H⋅2k+1, H⋅2k+1+2k)q \in [H\cdot 2^{k+1},\, H\cdot 2^{k+1} + 2^k): the bits of qq above kk are HH and bit kk of qq is 0. Conversely, for each kk with bit kk of qq zero there is exactly one such jj,

jk=(q∣(2k−1))+1,j_k = \big(q \mathbin{|} (2^k - 1)\big) + 1,

which copies the high bits of qq, sets bit kk to 1 and leaves zeros below. Thus the blocks containing pp are jk≤nj_k \le n, one for each zero bit of qq.

It remains to show that the chain visits them in order. If k0k_0 is the lowest zero bit of qq, adding 1 to qq turns the ones below into zeros and sets bit k0k_0: p=q+1=jk0p = q + 1 = j_{k_0}. And if j=jkj = j_k, adding lowbit⁡(j)=2k\operatorname{lowbit}(j) = 2^k propagates a carry through the ones of qq above bit kk and stops at the next zero bit k′k' of qq: the result is jk′j_{k'}. The chain therefore visits jkj_k for the zero bits of qq in increasing order, and since jkj_k increase with kk, it stops on exceeding nn. There is at most one jk≤nj_k \le n per k≤⌊log⁡2n⌋k \le \lfloor \log_2 n \rfloor.

∎

With p=5p = 5, q=4=001002q = 4 = 00100_2 has zeros at bits 0, 1, 3 and 4, and the blocks are j0=5j_0 = 5, j1=6j_1 = 6, j3=8j_3 = 8 and j4=16j_4 = 16: chain 5→6→8→165 \to 6 \to 8 \to 16. In the figure, the vertical through p=5p = 5 crosses exactly those four blocks.

Together the two theorems give a useful corollary: if p≤rp \le r, exactly one of the blocks used by the rr query contains pp (because they partition (0,r](0, r]), and that block is in the update chain of pp. This is why an update followed by a query is correct: the change in apa_p enters the sum exactly once. If p>rp > r, no query block contains pp, so the change does not enter.

Construction, k-th search and ranges

Construction in O(n)\bigO(n). Instead of nn updates (O(nlog⁡n)\bigO(n \log n)), copy aa into tt and traverse i=1,…,ni = 1, \dots, n adding tit_i to ti+lowbit⁡(i)t_{i + \operatorname{lowbit}(i)}. By the preceding theorem, i+lowbit⁡(i)i + \operatorname{lowbit}(i) is the smallest block strictly containing that of ii: its “parent”. When ii is processed, all its children, which are smaller than ii, have already contributed to it.

The k-th in O(log⁡n)\bigO(\log n). If aia_i are nonnegative, prefix sums are increasing and it makes sense to find the least ii with Pi≥kP_i \ge k: the symbol for a cumulative frequency, percentile bucket or line containing a byte. Binary search on PP would make log⁡n\log n queries costing log⁡n\log n. But the tree lets us decide answer bits from highest to lowest with one access per bit: maintain position pos\mathit{pos} (initially 0) with Ppos<kP_{\mathit{pos}} < k, and for 2j=2⌊log⁡2n⌋,…,2,12^j = 2^{\lfloor \log_2 n \rfloor}, \dots, 2, 1 try advancing to pos+2j\mathit{pos} + 2^j. Since pos\mathit{pos} is a sum of powers larger than 2j2^j, it is a multiple of 2j+12^{j+1}, so lowbit⁡(pos+2j)=2j\operatorname{lowbit}(\mathit{pos} + 2^j) = 2^j and tpos+2jt_{\mathit{pos} + 2^j} is exactly the sum of (pos,pos+2j](\mathit{pos}, \mathit{pos} + 2^j]. If pos+2j≤n\mathit{pos} + 2^j \le n and that block sums to less than the remainder, advance and subtract it; otherwise the kk-th lies inside that block and we try one half as long. At the end the answer is pos+1\mathit{pos} + 1. This is binary search on the answer using blocks the tree already summed.

Ranges. The sum of [l,r][l, r] is Pr−Pl−1P_r - P_{l-1}: two queries. For “add vv in [l,r][l, r]” with point queries, one Fenwick tree over the difference array suffices. To support both range updates and range queries there is a two-tree trick: if DD is the difference array, Pr=∑i≤r∑j≤iDj=∑j≤rDj (r−j+1)=r∑j≤rDj−∑j≤rDj (j−1)P_r = \sum_{i \le r} \sum_{j \le i} D_j = \sum_{j \le r} D_j\,(r - j + 1) = r\sum_{j \le r} D_j - \sum_{j \le r} D_j\,(j - 1). Maintain two Fenwick trees, one with DjD_j and one with Dj (j−1)D_j\,(j - 1); it is implemented in the lab below.

The segment tree

The segment tree applies divide and conquer to the array itself and stores the result of each subproblem.

It has 2n−12n - 1 nodes, height ⌈log⁡2n⌉\lceil \log_2 n \rceil, and is stored like a heap: root at position 1 and children of xx at 2x2x and 2x+12x + 1 (4n4n positions suffice for any nn). The three operations are short recursions:

  • Build: each node combines its children’s aggregates, O(n)\bigO(n).
  • Update apa_p: change the leaf and recombine its ancestors, at most ⌈log⁡2n⌉\lceil \log_2 n \rceil.
  • Query [l,r)[l, r): from the root, a node disjoint from the range returns ee, one contained returns its aggregate without descending, and a partial one combines its two children’s answers in order.

That a query costs O(log⁡n)\bigO(\log n) is not obvious: a long range covers many leaves. The key is that each level can have only two partial nodes, those containing range boundaries; you will prove this step by step in the exercises. The range is expressed as the union of at most 2⌈log⁡2n⌉2\lceil \log_2 n \rceil contained nodes.

Why a monoid is enough

Associativity is exactly what allows splitting the interval wherever suits the tree, not the user. Identity is only needed for disjoint nodes. Commutativity is not required, provided children are combined in order, left before right. This opens the door to aggregates that are not numbers:

Other useful monoids include matrix product (a node stores the ordered product of matrices in its interval, enabling affine transformation composition or evaluating linear recurrences over a range), composition of functions of a closed type, and the pair (minimum, number of occurrences).

Lazy propagation

Now suppose updates also cover ranges: “add 3 to every element of [l,r)[l, r)”. Updating leaf by leaf costs O(n)\bigO(n). The lazy idea mirrors querying: if a node lies entirely inside the range, update its aggregate and record a tag there with the pending update for descendants, without visiting them. The tag moves down to children only when a later operation needs to enter that node.

For this to work, updates must satisfy two algebraic conditions worth writing down, because they capture everything that can go wrong.

The key operation is push: before descending to children of a node with tag τ\tau, apply τ\tau to each child’s aggregate, compose it with the child’s existing tag, τ∘τhijo\tau \circ \tau_{\text{hijo}}, and reset the parent tag to identity. Composition order matters: what the child already had pending happened before what arrives from the parent.

Proof

Initially all tags are identity and aggregates exact. It suffices to see the three operations preserve the invariant. An operation only enters a node after pushing all ancestor tags, so at that moment they are all identity. (1) Apply ff to node xx contained in the range: new aggregate f(agg(x))f(\mathrm{agg}(x)) is the real one because ff is an endomorphism applied to all interval elements. For descendant zz of xx, the invariant expression gains ff outside its existing tags, exactly what happened to its elements: pending operations first, then ff. (2) Push from xx changes agg(c)\mathrm{agg}(c) to τ(x)(agg(c))\tau(x)(\mathrm{agg}(c)) and τ(c)\tau(c) to τ(x)∘τ(c)\tau(x) \circ \tau(c) in each child cc, and sets τ(x)=id\tau(x) = \mathrm{id}: for cc and every descendant of cc the total composition stays unchanged. (3) Recombine agg(x)=agg(2x)⊕agg(2x+1)\mathrm{agg}(x) = \mathrm{agg}(2x) \oplus \mathrm{agg}(2x+1) is done with τ(x)=id\tau(x) = \mathrm{id} and no tags above, when children are already exact.

∎

The table collects common cases. In all, cost per operation is O(log⁡n)\bigO(\log n): the same nodes as a query are visited, plus one push per partial node.

AggregateUpdateTagComposition “gg after ff”
minimumadd vvvvvf+vgv_f + v_g
minimum or maximumassign ccccmost recent wins, cgc_g
sum with length: (s,ℓ)(s, \ell)add vv: (s+vℓ,ℓ)(s + v\ell, \ell)vvvf+vgv_f + v_g
sum with lengthaffine x↦αx+βx \mapsto \alpha x + \beta: (αs+βℓ,ℓ)(\alpha s + \beta\ell, \ell)(α,β)(\alpha, \beta)(αgαf, αgβf+βg)(\alpha_g\alpha_f,\ \alpha_g\beta_f + \beta_g)
minimum and maximumaffine with α\alpha of any sign(α,β)(\alpha, \beta)as above; if α<0\alpha < 0, minimum and maximum swap

Two observations. A sum aggregate must carry interval length: “add vv” changes the sum by vℓv\ell, and without ℓ\ell it is not an endomorphism of the sum monoid. The affine family also handles the most error-prone case, mixing add and assign: “add vv” is (1,v)(1, v), “assign cc” is (0,c)(0, c), and the noncommutative final-column composition automatically does the right thing. Assign 5 then add 2 is (1,2)∘(0,5)=(0,7)(1, 2) \circ (0, 5) = (0, 7); add 2 then assign 5 is (0,5)∘(1,2)=(0,5)(0, 5) \circ (1, 2) = (0, 5).

A rigor detail about row two. With minimum as aggregate, “assign cc” is constant map x↦cx \mapsto c, which respects ⊕\oplus (min⁡(c,c)=c\min(c, c) = c) but does not fix the identity: it maps e=+∞e = +\infty to cc. This does no harm because the tree only applies tags to nonempty-interval aggregates, never to ee, which appears only as the answer for disjoint nodes; to satisfy the definition literally, define assignment as cc on finite values and +∞+\infty on +∞+\infty. The same applies to affine maps with α=0\alpha = 0 on minima and maxima. For sum and length the problem does not arise: identity (0,0)(0, 0) maps to (0⋅0+c⋅0,0)=(0,0)(0 \cdot 0 + c \cdot 0, 0) = (0, 0).

InteractiveSegment tree with lazy tags
25255+34+3256+32415625863927461856972Array real (lo que debería haber en las hojas)50819263124551067798491110811612913714215
  • fully covered: use or tag
  • partially covered: push and descend
  • pending tag
  • stale node: a pending tag is above it
Starting state: 3 was lazily added on [2, 12]. Internal nodes [2, 3], [4, 7] and [8, 11] carry the +3 tag (leaf [12] is updated without a tag), and their descendants (dashed border) have not yet received it.
Range
4
11
5
Nodes visited0
Pending tags3
Incorrect queries0 of 0
Range minima on 16 leaves, with range ‘add vv’ and ‘assign vv’. The initial state already has an addition of 3 pending: [2,12][2, 12] was decomposed into [2,3][2, 3], [4,7][4, 7], [8,11][8, 11] and leaf [12][12], which was updated directly; the three internal nodes have tag +3+3 (magenta), while their descendants with dashed borders still hold old values; the real array is below. Run a minimum query entering one of those nodes and see the tag descend only along the query path. Then enable incorrect composition, which keeps the previous pending addition upon assignment: ‘Assign 5’ on [4,11][4, 11] followed by the minimum on [4,11][4, 11] works, but the minimum on [6,6][6, 6] fails. The error stays hidden until a query descends.

The experiment shows why such errors are treacherous: incorrect composition does not spoil the updated node’s aggregate (calculated by applying the new tag to its value), but the tag it stores for its children. Queries answered by that entire node remain correct; only those descending below it fail, sometimes much later. Tests should therefore mix random operations and compare against a naive version, as in the lab.

Sparse tables: minima in O(1)\bigO(1)

If data do not change and minimum is requested (the range minimum query, RMQ), one can improve on O(log⁡n)\bigO(\log n). The sparse table precomputes the minimum of every power-of-two-length window:

Tk,i=min⁡(ai,…,ai+2k−1),T0,i=ai,Tk,i=min⁡ ⁣(Tk−1,i, Tk−1, i+2k−1).T_{k,i} = \min(a_i, \dots, a_{i + 2^k - 1}), \qquad T_{0,i} = a_i, \qquad T_{k,i} = \min\!\big(T_{k-1,i},\ T_{k-1,\,i + 2^{k-1}}\big).

Level kk has n−2k+1n - 2^k + 1 entries and there are ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 levels: O(nlog⁡n)\bigO(n \log n) in time and memory. To query [l,r][l, r], take k=⌊log⁡2(r−l+1)⌋k = \lfloor \log_2(r - l + 1) \rfloor and cover the ends with two windows of length 2k2^k, one starting at ll and one ending at rr:

min⁡(al,…,ar)=min⁡(Tk,l, Tk, r−2k+1).\min(a_l, \dots, a_r) = \min\big(T_{k,l},\ T_{k,\,r - 2^k + 1}\big).
Proof

Since 2k≤r−l+1<2k+12^k \le r - l + 1 < 2^{k+1}, both windows lie within [l,r][l, r] and together cover it. Call AA the portion covered only by the first, BB the overlap and CC the portion covered only by the second (which occur in that order, with BB possibly empty; if BB is empty there is nothing to prove). The first window is A⊕BA \oplus B and the second B⊕CB \oplus C, so associativity and idempotence give (A⊕B)⊕(B⊕C)=A⊕(B⊕B)⊕C=A⊕B⊕C(A \oplus B) \oplus (B \oplus C) = A \oplus (B \oplus B) \oplus C = A \oplus B \oplus C.

∎

Commutativity is unnecessary, but idempotence is essential: with sum, overlap BB would be counted twice. Minimum, maximum, greatest common divisor, bitwise AND and OR are idempotent; sum, XOR and product are not. For associative non-idempotent operations there is a disjoint sparse table, which stores aggregates toward both sides of each split point at every level and answers using two nonoverlapping windows, also in O(1)\bigO(1) after O(nlog⁡n)\bigO(n \log n). To calculate ⌊log⁡2m⌋\lfloor \log_2 m \rfloor in O(1)\bigO(1), use a machine instruction (bit_length in Python, __builtin_clz in C) or a precomputed table.

Linear preprocessing with blocks

Can preprocessing be reduced to O(n)\bigO(n) without losing O(1)\bigO(1) queries? Yes, by splitting the array into blocks of size b=⌈12log⁡2n⌉b = \lceil \tfrac{1}{2}\log_2 n \rceil:

  1. Between blocks: each block’s minimum forms an array of n/bn/b elements, and its sparse table costs O(nblog⁡nb)=O(n)\bigO\big(\tfrac{n}{b}\log\tfrac{n}{b}\big) = \bigO(n).
  2. Prefixes and suffixes: minimum of each prefix and suffix of each block, O(n)\bigO(n) in total.
  3. Inside one block: the hard case, when ll and rr fall in the same block.

A query crossing multiple blocks is the first block’s suffix, the sparse table over intermediate blocks and the last block’s prefix: O(1)\bigO(1). For the third case, Bender and Farach-Colton (2000) observed that in ±1 arrays, where consecutive elements differ by exactly 1, the minimum position of any subrange of a block depends only on the sequence of b−1b - 1 rises and falls, not the initial value. There are at most 2b−1≤n2^{b-1} \le \sqrt{n} distinct sequences, and answers to all their O(b2)\bigO(b^2) subqueries can be precomputed in O(n log⁡2n)=o(n)\bigO(\sqrt{n}\,\log^2 n) = o(n). Each block stores its sequence number and a query is a table read. Total: O(n)\bigO(n) preprocessing and O(1)\bigO(1) per query for ±1 RMQ. The next section shows where ±1 arrays arise and how they also solve general RMQ.

LCA and RMQ: two sides of the same problem

In a rooted tree, the lowest common ancestor lca⁡(u,v)\operatorname{lca}(u, v) is the deepest node that is an ancestor of both (a node counts as its own ancestor). It is fundamental in phylogenies, class hierarchies, version-control systems (a merge base is a common ancestor), and any tree-distance query, because

d(u,v)=prof⁡(u)+prof⁡(v)−2 prof⁡(lca⁡(u,v)).d(u, v) = \operatorname{prof}(u) + \operatorname{prof}(v) - 2\,\operatorname{prof}\big(\operatorname{lca}(u, v)\big).

Climbing from both nodes until they meet costs the tree height, which can be Θ(n)\Theta(n). The reduction between LCA and RMQ turns it into a minimum query:

  • The Euler tour EE is the sequence of nodes written by a depth-first traversal, recording each node on entry and whenever returning from a child. It has 2n−12n - 1 entries, since each of the n−1n - 1 edges is traversed twice.
  • Let primera⁡(u)\operatorname{primera}(u) be the position of the first occurrence of uu in EE.
  • Then lca⁡(u,v)\operatorname{lca}(u, v) is the minimum-depth node in EE between primera⁡(u)\operatorname{primera}(u) and primera⁡(v)\operatorname{primera}(v).
InteractiveLCA as a range minimum
ABCDEFGHIJKuvdepth 0depth 1depth 2depth 3Euler tour E (2n − 1 = 21 positions)A0BE2BF4J5F6KF8BA10CG12CA14DH16DI18DA20depth of E[k] (deeper is lower)
  • uu and its first occurrence
  • vv and its first occurrence
  • tour and depth profile
  • minimum of range = LCA
RMQ query
Between the first occurrences of u=Ju = J (position 5) and v=Ev = E (position 2), the tour never rises above B and passes through it: the minimum depth is B, matching the LCA.
Next click changes
First occurrence of uu, vv5, 2
Range of EE[2, 5]
Minimum depth1 (pos. 3)
LCA via RMQB
LCA by climbing parentsB
Distance d(u)+d(v)−2d(lca)d(u) + d(v) - 2d(\mathrm{lca})3
Choose two tree nodes (clicks alternate between uu and vv). At the top the tree is traversed depth-first; in the middle the Euler tour is written, with 21 positions for 11 nodes; below is the sequence's depth profile, a mountain range in which each step rises or falls exactly 1. The shaded range runs from the first occurrence of uu to that of vv, and its shallowest point (highest on the profile, drawn with the root at the top like the tree), in magenta, is the LCA, highlighted in the tree along with the path from uu to vv. Try a node and one of its descendants, two leaves in different root branches, and u=vu = v. Replay the animation to see the sequence written.

The reason is the parenthesis structure of depth-first traversal (the parenthesis theorem in lesson 18): traversal enters a node’s subtree, visits it completely without leaving, then returns to the parent. Between the first appearances of uu and vv the traversal does not leave the LCA’s subtree, so it never passes anything shallower and must pass the LCA itself to go from the uu branch to the vv branch. You will prove this in detail in the exercises.

The depth profile is a ±1 array, the case the block algorithm solves in O(n)\bigO(n) and O(1)\bigO(1). Thus LCA has linear preprocessing and constant queries. The circle also closes in reverse: general RMQ reduces to LCA through the array’s Cartesian tree, whose root is the minimum’s position and whose left and right subtrees are Cartesian trees of the two halves. The minimum of al,…,ara_l, \dots, a_r is at lca⁡(l,r)\operatorname{lca}(l, r) of that tree, built in O(n)\bigO(n) with a stack. General RMQ → LCA → ±1 RMQ: linear time and constant queries for any array. The first optimal LCA algorithms, by Harel and Tarjan (1984) and Schieber and Vishkin (1988), were notoriously hard to implement; Bender and Farach-Colton (2000) gave this simple version, a sequentialization of a parallel algorithm by Berkman, Breslauer, Galil, Schieber and Vishkin (1989).

Binary lifting

In practice another technique competes with a sparse table on the Euler tour: binary lifting. Precompute arribak(v)\mathrm{arriba}_k(v), the ancestor of vv 2k2^k levels up, with recurrence arribak(v)=arribak−1(arribak−1(v))\mathrm{arriba}_k(v) = \mathrm{arriba}_{k-1}\big(\mathrm{arriba}_{k-1}(v)\big), in O(nlog⁡n)\bigO(n \log n). To climb dd levels, decompose dd in binary and take one jump per set bit: the same idea as fast exponentiation, with the parent function instead of a number and composition instead of multiplication. For LCA, equalize depths and then climb from both nodes together with decreasing jumps while their ancestors differ: O(log⁡n)\bigO(\log n) per query. It is slower than a sparse table but also answers “the kk-th ancestor” and extends to path aggregates (minimum edge weight between uu and vv, for example).

Augmented trees

So far positions were fixed: element 7 stays seventh forever. But many range queries concern keys: how many latencies lie between 120 and 300 ms, what is the median of observed prices, which reservations overlap this interval. Inserting a new key shifts all following positions, which an array handles poorly. The solution is to store aggregates in a balanced binary search tree.

Proof

Changing ff at a node can only change ff at its ancestors, of which there are O(log⁡n)\bigO(\log n): recompute them bottom-up. Insertion and deletion modify the tree in two places: the root-to-inserted-or-deleted-node path, recomputed this way, and rotations. A rotation changes only the subtrees of the two nodes exchanging positions, so recompute ff at those two, lower node first; ancestors do not change because their subtree still contains the same nodes. A red-black tree has at most two rotations per insertion and three per deletion.

∎

The statement also says what cannot be maintained. Node depth depends on ancestors rather than children, and a rotation changes it for an entire subtree. A node’s global position (rank) changes for every larger-key node whenever a small key is inserted. Neither is an augmented field; rank, however, can be computed in O(log⁡n)\bigO(\log n) from sizes.

The order-statistic tree

The canonical example stores tam(x)\mathrm{tam}(x), the number of nodes in xx‘s subtree, with tam(x)=tam(x.izq)+tam(x.der)+1\mathrm{tam}(x) = \mathrm{tam}(x.\mathrm{izq}) + \mathrm{tam}(x.\mathrm{der}) + 1. With it:

  • select(i)(i), the key of rank ii: at node xx, let r=tam(x.izq)+1r = \mathrm{tam}(x.\mathrm{izq}) + 1. If i=ri = r, it is xx; if i<ri < r, find the ii-th on the left; if i>ri > r, the (i−r)(i - r)-th on the right.
  • rank(k)(k), how many keys are smaller than kk: while descending in search of kk, whenever turning right add the left subtree and node.
  • Count in a range: the number of keys in [k1,k2)[k_1, k_2) is rank⁡(k2)−rank⁡(k1)\operatorname{rank}(k_2) - \operatorname{rank}(k_1).

On insertion increment tam\mathrm{tam} along the entire descent path and, in each rotation raising yy above xx, set tam(y)←tam(x)\mathrm{tam}(y) \leftarrow \mathrm{tam}(x) (the entire subtree now hangs from yy) and recompute tam(x)\mathrm{tam}(x) from its new children. Forget those two lines and the tree remains a valid red-black tree with working searches, but select and rank return garbage. You will see this in the lab.

When keys are known beforehand (or can be processed offline), a simpler and faster alternative exists: compress keys to 1,…,m1, \dots, m by order and use a Fenwick tree of frequencies. “Count keys in a range” is a range sum and select is the kk-th search. Fenwick cannot accept keys outside the initial universe; an augmented tree can.

The interval tree

To store intervals [lo,hi][\mathit{lo}, \mathit{hi}] and ask which overlap a given interval, use a red-black tree ordered by lo\mathit{lo} where each node stores max(x)\mathrm{max}(x), its subtree’s greatest right endpoint: max(x)=max⁡(x.hi, max(x.izq), max(x.der))\mathrm{max}(x) = \max\big(x.\mathit{hi},\ \mathrm{max}(x.\mathrm{izq}),\ \mathrm{max}(x.\mathrm{der})\big). It is an augmented field, so it is maintained at no extra asymptotic cost. To find an interval overlapping [loq,hiq][\mathit{lo}_q, \mathit{hi}_q]:

  • if xx overlaps, return it;
  • if max(x.izq)≥loq\mathrm{max}(x.\mathrm{izq}) \ge \mathit{lo}_q, descend left;
  • otherwise descend right.

Descending right when the left maximum is less than loq\mathit{lo}_q is clearly safe: everything on the left ends earlier. The other decision is subtler. If max(x.izq)≥loq\mathrm{max}(x.\mathrm{izq}) \ge \mathit{lo}_q, there is an interval i′i' on the left with i′.hi≥loqi'.\mathit{hi} \ge \mathit{lo}_q. If no left interval overlaps the query, neither does i′i', and since it ends after loq\mathit{lo}_q, it must start after hiq\mathit{hi}_q: i′.lo>hiqi'.\mathit{lo} > \mathit{hi}_q. All right intervals start later still (the tree is ordered by lo\mathit{lo}), so they do not overlap either. Going left never loses an answer. One search costs O(log⁡n)\bigO(\log n), and listing the kk overlaps costs O(min⁡(n,(k+1)log⁡n))\bigO(\min(n, (k+1)\log n)).

Spatial ranges: quadtrees and octrees

Everything above aggregates intervals on a line. In the plane the natural questions are “how many points are in this rectangle?” or “which point is closest to this one?”. Two-dimensional prefix sums solve the first if points live on a fixed grid. For arbitrary coordinates, hierarchical blocks generalize by splitting space.

Subdivision is adaptive: where many points cluster the tree is deep, and where none exist it remains a large empty cell. The cost is that depth depends not on point count but on their proximity. With capacity 1, two points at distance δ\delta in a square of side ss may require many subdivisions: a cell containing both has diagonal at least δ\delta, so they separate at latest when cell diagonal drops below δ\delta; if both fall in a small cell of the hierarchy with no dividing line between them until deep down, nearly that depth is needed. Depth is therefore on the order of log⁡2(s/δ)\log_2(s/\delta); de Berg and coauthors (Computational Geometry, chapter 14) give bound log⁡2(s/δ)+3/2\log_2(s/\delta) + 3/2 and prove a tree of depth pp has O((p+1) n)\bigO((p + 1)\,n) nodes. Two almost coincident points can generate a very long chain of cells with one useful child; real implementations therefore cap depth or compress chains.

InteractiveQuadtree: ranges and Barnes-Hut
  • contained cell: add its count
  • boundary leaf: examine its points
  • point inside
The count uses 4 whole cells and 20 individual points in boundary leaves: the work grows with the rectangle’s perimeter, not its area.
Query
4
Nodes / leaves / height165 / 124 / 6
Points in rectangle59
Nodes visited29
Cells counted whole4
Points examined20 of 180
One hundred eighty points in three clusters and a uniform background. In range mode, drag the rectangle or its corners. Fully contained cells (aquamarine) contribute their count without descending, disjoint ones are pruned, and only points of leaves crossing the boundary (orange) are examined individually. Compare visited nodes with the 180 points and observe work follows the rectangle's perimeter. Change capacity cc: with c=1c = 1 the tree becomes deep in clusters. In Barnes-Hut mode, click a point and move θ\theta: each cell that looks small from the point (side less than θ\theta times distance to its center of mass) is replaced by one mass at that center. With θ=0\theta = 0 the calculation is exact; with θ=0.5\theta = 0.5 and c=4c = 4, the initial point uses 54 of 179 interactions with 0.8% error. Raise θ\theta above 1 and try several points: for many error exceeds 10%, because cells closer than their own size are accepted and no longer resemble a point mass.

Range queries. Recursion matches the segment tree: prune disjoint cells; use the aggregate of contained cells; descend into partial cells. Partial cells cross the rectangle boundary, and at level jj (side 2−j2^{-j} in the unit square) a boundary of length LL crosses on the order of L 2jL\,2^j cells. With reasonably distributed points the tree has depth near log⁡4n\log_4 n and summing across levels gives on the order of n\sqrt{n} boundary cells, plus kk answers if listing them. This is not a worst-case guarantee: k-d trees split at the median on alternating axes and guarantee O(n+k)\bigO(\sqrt{n} + k) in the plane.

Nearest neighbor. Traverse the tree with a priority queue ordered by the query point’s distance to each cell, pruning any cell farther away than the best candidate found. This is geometry-guided branch and bound.

Cell aggregation: Barnes-Hut. Computing gravitational (or electrostatic) force exerted by nn bodies on each one costs Θ(n2)\Theta(n^2). Barnes and Hut (1986) observed that from far away, a cell with many bodies attracts almost like a single body with their total mass at their center of mass, and that aggregate is a monoid: the pair (mass, mass times position) adds. For each body traverse the octree from the root: if cell side ss and distance dd to its center of mass satisfy s/d<θs/d < \theta, use the aggregate; otherwise descend. With reasonable distributions each body interacts with O(log⁡n)\bigO(\log n) cells and the total is O(nlog⁡n)\bigO(n \log n); θ\theta trades accuracy for speed. The same trick accelerates t-SNE: van der Maaten’s Barnes-Hut version (2014), used by scikit-learn by default, approximates t-SNE repulsive forces with a quadtree, and its parameter angle (0.5 by default) is this θ\theta. Greengard and Rokhlin’s fast multipole method (1987) goes a step further, with series expansions instead of point masses, reducing to O(n)\bigO(n).

Implementation from scratch

The lab builds a small range-query library and tests it by properties: each structure faces a naive NumPy version across thousands of random operations. With these structures errors are rarely in cases one imagines, but in operation combinations that only arise randomly. First, one- and two-dimensional prefix sums and the difference array.

[ ]1D and 2D prefix sums and differencesBrowser
import numpy as np

def prefijas(a):
    """P[i] = a[0] + ... + a[i-1], con P[0] = 0: la suma de a[l:r] es P[r] - P[l]."""
    P = [0] * (len(a) + 1)
    for i, x in enumerate(a):
        P[i + 1] = P[i] + x
    return P

def prefijas_2d(A):
    """S[i][j] = suma del rectángulo A[0:i, 0:j]; una fila y una columna de ceros delante."""
    n, m = len(A), len(A[0])
    S = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(n):
        for j in range(m):
            S[i + 1][j + 1] = A[i][j] + S[i][j + 1] + S[i + 1][j] - S[i][j]
    return S

def suma_rect(S, r0, c0, r1, c1):
    """Suma de A[r0:r1, c0:c1] por inclusión-exclusión: cuatro lecturas."""
    return S[r1][c1] - S[r0][c1] - S[r1][c0] + S[r0][c0]

def aplicar_diferencias(n, actualizaciones):
    """Cada (l, r, v) suma v a a[l:r]: dos marcas por actualización y una suma prefija al final."""
    D = [0] * (n + 1)
    for l, r, v in actualizaciones:
        D[l] += v
        D[r] -= v
    return prefijas(D)[1:n + 1]

rng = np.random.default_rng(0)
a = rng.integers(-50, 50, size=1000)
P = prefijas(a.tolist())
for _ in range(200):
    l, r = sorted(rng.integers(0, 1001, size=2))
    assert P[r] - P[l] == a[l:r].sum()

A = rng.integers(0, 10, size=(60, 80))
S = prefijas_2d(A.tolist())
for _ in range(200):
    r0, r1 = sorted(rng.integers(0, 61, size=2))
    c0, c1 = sorted(rng.integers(0, 81, size=2))
    assert suma_rect(S, r0, c0, r1, c1) == A[r0:r1, c0:c1].sum()

ups = [(int(l), int(r), int(v)) for l, r, v in zip(rng.integers(0, 500, 300), rng.integers(500, 1001, 300), rng.integers(-5, 6, 300))]
ref = np.zeros(1000, dtype=int)
for l, r, v in ups:
    ref[l:r] += v
assert np.array_equal(aplicar_diferencias(1000, ups), ref)
print("1D: 200 sumas de rango correctas, dos lecturas cada una")
print("2D: 200 rectángulos correctos, cuatro lecturas cada uno")
print("diferencias: 300 actualizaciones de rango con 600 marcas y una sola pasada")

The Fenwick tree, one-indexed inside the class, with linear construction, kk-th search and the two-tree range variant. The final part counts how many indices each operation touches in a tree of 2202^{20} positions.

[ ]Fenwick treeBrowser
class Fenwick:
    """Árbol de Fenwick con índices desde 1: t[i] guarda la suma de a(i - lowbit(i), i]."""

    def __init__(self, n):
        self.n = n
        self.t = [0] * (n + 1)

    @classmethod
    def desde(cls, valores):
        """Construcción en O(n): cada t[i] se vuelca en su padre i + lowbit(i)."""
        f = cls(len(valores))
        f.t[1:] = list(valores)
        for i in range(1, f.n + 1):
            j = i + (i & -i)
            if j <= f.n:
                f.t[j] += f.t[i]
        return f

    def sumar(self, i, delta):           # a[i] += delta
        while i <= self.n:
            self.t[i] += delta
            i += i & -i

    def prefijo(self, i):                # a[1] + ... + a[i]
        s = 0
        while i > 0:
            s += self.t[i]
            i -= i & -i
        return s

    def rango(self, l, r):               # a[l] + ... + a[r]
        return self.prefijo(r) - self.prefijo(l - 1)

    def kesimo(self, k):
        """Menor i con prefijo(i) >= k (frecuencias no negativas). Devuelve n + 1 si no existe."""
        pos, paso = 0, 1 << self.n.bit_length()
        while paso:
            nxt = pos + paso
            if nxt <= self.n and self.t[nxt] < k:
                pos, k = nxt, k - self.t[nxt]
            paso >>= 1
        return pos + 1

class FenwickRango:
    """Sumar v en [l, r] y sumar a[l..r], ambas en O(log n), con dos Fenwick sobre las diferencias."""

    def __init__(self, n):
        self.b1, self.b2, self.n = Fenwick(n), Fenwick(n), n

    def sumar_rango(self, l, r, v):
        for i, w in ((l, v), (r + 1, -v)):
            if i <= self.n:
                self.b1.sumar(i, w)
                self.b2.sumar(i, w * (i - 1))

    def prefijo(self, i):
        return self.b1.prefijo(i) * i - self.b2.prefijo(i)

    def rango(self, l, r):
        return self.prefijo(r) - self.prefijo(l - 1)

rng = np.random.default_rng(1)
n = 1000
a = rng.integers(0, 20, size=n + 1); a[0] = 0          # a[0] no se usa: índices desde 1
f = Fenwick.desde(a[1:].tolist())
for paso in range(3000):
    op = rng.integers(3)
    if op == 0:
        i, d = int(rng.integers(1, n + 1)), int(rng.integers(0, 10))
        f.sumar(i, d); a[i] += d
    elif op == 1:
        l, r = sorted(rng.integers(1, n + 1, size=2))
        assert f.rango(int(l), int(r)) == a[l:r + 1].sum()
    else:
        c = np.cumsum(a)
        k = int(rng.integers(1, c[-1] + 1))
        assert f.kesimo(k) == int(np.searchsorted(c, k)), k
print("Fenwick: 3000 operaciones mezcladas (sumar, rango, k-ésimo) coinciden con NumPy")

g = FenwickRango(n)
b = np.zeros(n + 1, dtype=np.int64)
for paso in range(3000):
    l, r = sorted(int(x) for x in rng.integers(1, n + 1, size=2))
    if rng.random() < 0.5:
        v = int(rng.integers(-9, 10))
        g.sumar_rango(l, r, v); b[l:r + 1] += v
    else:
        assert g.rango(l, r) == b[l:r + 1].sum()
print("Fenwick de rangos: 3000 operaciones correctas")

def accesos_prefijo(i):
    c = 0
    while i > 0:
        c += 1; i -= i & -i
    return c

def accesos_sumar(i, n):
    c = 0
    while i <= n:
        c += 1; i += i & -i
    return c

N = 1 << 20
muestra = rng.integers(1, N + 1, size=20000)
print(f"n = 2^20: prefijo visita en media {np.mean([accesos_prefijo(int(i)) for i in muestra]):.2f} índices "
      f"(máx {max(accesos_prefijo(int(i)) for i in muestra)}); sumar, {np.mean([accesos_sumar(int(i), N) for i in muestra]):.2f}")

For a random 20-bit index, a query touches about 10 indices on average (set bits, half of 20) and an update about 11 (zero bits of p−1p - 1 plus the upper one). Far fewer than the million elements underneath.

Now the generic segment tree. The class knows nothing about minima or sums: it receives the monoid (op, e) and update family (aplicar, componer, ident), just like the definition. componer(g, f) means “first ff, then gg”.

[ ]Generic segment tree with lazy propagationBrowser
import math

class LazySegTree:
    """Árbol de segmentos sobre un monoide (op, e) con actualizaciones (aplicar, componer, ident).
    Rangos semiabiertos [l, r) y raíz en el nodo 1."""

    def __init__(self, valores, op, e, aplicar, componer, ident):
        self.op, self.e, self.aplicar, self.componer, self.ident = op, e, aplicar, componer, ident
        self.n = len(valores)
        self.agg = [e] * (4 * self.n)
        self.tag = [ident] * (4 * self.n)
        self._construir(1, 0, self.n, valores)

    def _construir(self, x, lo, hi, v):
        if hi - lo == 1:
            self.agg[x] = v[lo]
            return
        mid = (lo + hi) // 2
        self._construir(2 * x, lo, mid, v)
        self._construir(2 * x + 1, mid, hi, v)
        self.agg[x] = self.op(self.agg[2 * x], self.agg[2 * x + 1])

    def _poner(self, x, f):              # f llega a x: actualiza su agregado y la deja pendiente para sus hijos
        self.agg[x] = self.aplicar(f, self.agg[x])
        self.tag[x] = self.componer(f, self.tag[x])     # primero lo que había, después f

    def _empujar(self, x):
        if self.tag[x] != self.ident:
            self._poner(2 * x, self.tag[x])
            self._poner(2 * x + 1, self.tag[x])
            self.tag[x] = self.ident

    def actualizar(self, l, r, f, x=1, lo=0, hi=None):
        hi = self.n if hi is None else hi
        if r <= lo or hi <= l:
            return
        if l <= lo and hi <= r:
            self._poner(x, f)
            return
        self._empujar(x)
        mid = (lo + hi) // 2
        self.actualizar(l, r, f, 2 * x, lo, mid)
        self.actualizar(l, r, f, 2 * x + 1, mid, hi)
        self.agg[x] = self.op(self.agg[2 * x], self.agg[2 * x + 1])

    def consultar(self, l, r, x=1, lo=0, hi=None):
        hi = self.n if hi is None else hi
        if r <= lo or hi <= l:
            return self.e
        if l <= lo and hi <= r:
            return self.agg[x]
        self._empujar(x)
        mid = (lo + hi) // 2
        return self.op(self.consultar(l, r, 2 * x, lo, mid), self.consultar(l, r, 2 * x + 1, mid, hi))

# Instancia 1: mínimo con «sumar v». Las actualizaciones son m -> m + v y componer es sumar.
def min_suma(valores):
    return LazySegTree(valores, min, math.inf, lambda v, m: m + v, lambda v2, v1: v1 + v2, 0)

# Instancia 2: suma con actualizaciones afines x -> a x + b, que incluyen «sumar v» = (1, v) y «asignar c» = (0, c).
# El agregado lleva la longitud: (s, len). Composición: (a2, b2) después de (a1, b1) = (a2 a1, a2 b1 + b2).
def suma_afin(valores, componer=None):
    op = lambda p, q: (p[0] + q[0], p[1] + q[1])
    aplicar = lambda f, p: (f[0] * p[0] + f[1] * p[1], p[1])
    bien = lambda f2, f1: (f2[0] * f1[0], f2[0] * f1[1] + f2[1])
    return LazySegTree([(v, 1) for v in valores], op, (0, 0), aplicar, componer or bien, (1, 0))

def prueba(fabrica, consulta_ref, ops=3000, n=300, semilla=2, afines=False):
    """Operaciones al azar contra NumPy. Devuelve el número de la primera operación que falla, o None."""
    rng = np.random.default_rng(semilla)
    ref = rng.integers(-20, 20, size=n).astype(np.int64)
    st = fabrica(ref.tolist())
    for k in range(ops):
        l, r = sorted(int(x) for x in rng.integers(0, n + 1, size=2))
        if l == r:
            continue
        u = rng.random()
        if u < 0.25:
            v = int(rng.integers(-9, 10))
            st.actualizar(l, r, (1, v) if afines else v); ref[l:r] += v
        elif u < 0.5 and afines:
            c = int(rng.integers(-9, 10))
            st.actualizar(l, r, (0, c)); ref[l:r] = c
        else:
            got = st.consultar(l, r)
            got = got[0] if afines else got
            if got != consulta_ref(ref[l:r]):
                return k
    return None

print("mínimo + sumar:       primer fallo en la operación", prueba(min_suma, np.min))
print("suma + afín:          primer fallo en la operación", prueba(suma_afin, np.sum, afines=True))
# El error típico: componer al revés (aplicar la etiqueta vieja DESPUÉS de la nueva)
al_reves = lambda f2, f1: (f1[0] * f2[0], f1[0] * f2[1] + f1[1])
print("suma + afín al revés: primer fallo en la operación", prueba(lambda v: suma_afin(v, al_reves), np.sum, afines=True))

Both correct instances pass 3000 operations without failure, and reversed composition fails at operation 4. Here the error appears early because one in four operations is assignment; with few assignments the same defect can take thousands of operations to appear, which is why tests must force mixes of every update type.

The sparse table, generic in the operation, versus NumPy with four associative operations, three idempotent and one not:

[ ]Sparse table and idempotenceBrowser
def tabla_dispersa(a, op):
    """T[k][i] = op de a[i : i + 2^k]. O(n log n) entradas."""
    T = [list(a)]
    k = 1
    while (1 << k) <= len(a):
        prev, h = T[-1], 1 << (k - 1)
        T.append([op(prev[i], prev[i + h]) for i in range(len(a) - (1 << k) + 1)])
        k += 1
    return T

def consulta_dispersa(T, op, l, r):
    """op de a[l..r] (cerrado) con dos ventanas de longitud 2^k que se solapan."""
    k = (r - l + 1).bit_length() - 1
    return op(T[k][l], T[k][r - (1 << k) + 1])

rng = np.random.default_rng(3)
a = rng.integers(1, 10**6, size=5000).tolist()
for nombre, op, ref in [("mín", min, np.min), ("mcd", math.gcd, np.gcd.reduce),
                        ("OR", lambda x, y: x | y, np.bitwise_or.reduce), ("suma", lambda x, y: x + y, np.sum)]:
    T = tabla_dispersa(a, op)
    malas = 0
    for _ in range(2000):
        l, r = sorted(int(x) for x in rng.integers(0, len(a), size=2))
        malas += consulta_dispersa(T, op, l, r) != ref(np.array(a[l:r + 1]))
    print(f"{nombre:5s}: {sum(map(len, T))} entradas, {malas} consultas erróneas de 2000")

With addition they all fail, even power-of-two lengths: the two windows then coincide and the result is doubled. The 56,822 entries for n=5000n = 5000 are ∑k=012(5001−2k)\sum_{k=0}^{12} (5001 - 2^k), about eleven times the array: memory is the price of constant-time queries.

LCA both ways, on a random tree of 3000 nodes, against the naive parent-climbing algorithm. The Euler tour uses an explicit stack because a degenerate tree would exhaust Python recursion.

[ ]LCA: Euler tour versus binary liftingBrowser
def arbol_aleatorio(n, rng):
    padre = [-1] + [int(rng.integers(0, v)) for v in range(1, n)]    # el padre de v es un nodo anterior
    hijos = [[] for _ in range(n)]
    for v in range(1, n):
        hijos[padre[v]].append(v)
    return padre, hijos

def euler(hijos, raiz=0):
    """Recorrido de Euler iterativo: secuencia E, profundidades y primera aparición."""
    n = len(hijos)
    prof, primera, E = [0] * n, [0] * n, []
    pila = [(raiz, 0)]                                  # (nodo, siguiente hijo por visitar)
    while pila:
        u, i = pila.pop()
        if i == 0:
            primera[u] = len(E)
        E.append(u)
        if i < len(hijos[u]):
            pila.append((u, i + 1))
            c = hijos[u][i]
            prof[c] = prof[u] + 1
            pila.append((c, 0))
    return E, prof, primera

class LCAEuler:
    def __init__(self, hijos):
        self.E, self.prof, self.primera = euler(hijos)
        pares = [(self.prof[u], u) for u in self.E]     # el mínimo por profundidad trae consigo el nodo
        self.T = tabla_dispersa(pares, min)

    def __call__(self, u, v):
        i, j = sorted((self.primera[u], self.primera[v]))
        return consulta_dispersa(self.T, min, i, j)[1]

class LCASaltos:
    """Saltos binarios: arriba[k][v] es el antecesor 2^k niveles por encima (la raíz se apunta a sí misma)."""
    def __init__(self, padre, prof):
        n, self.prof = len(padre), prof
        self.LOG = max(1, (n - 1).bit_length())
        self.arriba = [[p if p >= 0 else 0 for p in padre]]
        for k in range(1, self.LOG):
            prev = self.arriba[-1]
            self.arriba.append([prev[prev[v]] for v in range(n)])

    def __call__(self, u, v):
        if self.prof[u] < self.prof[v]:
            u, v = v, u
        d, k = self.prof[u] - self.prof[v], 0
        while d:                                        # sube d niveles: un salto por cada bit a 1 de d
            if d & 1:
                u = self.arriba[k][u]
            d >>= 1; k += 1
        if u == v:
            return u
        for k in range(self.LOG - 1, -1, -1):           # sube a la vez mientras los antecesores difieran
            if self.arriba[k][u] != self.arriba[k][v]:
                u, v = self.arriba[k][u], self.arriba[k][v]
        return self.arriba[0][u]

def lca_ingenuo(padre, u, v):
    anc = set()
    while u >= 0:
        anc.add(u); u = padre[u]
    while v not in anc:
        v = padre[v]
    return v

rng = np.random.default_rng(4)
padre, hijos = arbol_aleatorio(3000, rng)
lca_e = LCAEuler(hijos)
lca_s = LCASaltos(padre, lca_e.prof)
pares = [tuple(int(x) for x in rng.integers(0, 3000, size=2)) for _ in range(2000)]
assert all(lca_e(u, v) == lca_s(u, v) == lca_ingenuo(padre, u, v) for u, v in pares)
print(f"n = 3000: |E| = {len(lca_e.E)} = 2n - 1, altura {max(lca_e.prof)}")
print("2000 pares: Euler + tabla dispersa, saltos binarios e ingenuo coinciden")
dist = lambda u, v: lca_e.prof[u] + lca_e.prof[v] - 2 * lca_e.prof[lca_e(u, v)]
print("distancia media entre pares:", round(float(np.mean([dist(u, v) for u, v in pares])), 2))
assert all(abs(lca_e.prof[x] - lca_e.prof[y]) == 1 for x, y in zip(lca_e.E, lca_e.E[1:]))
print("profundidades consecutivas en E: siempre difieren en exactamente 1 (un array ±1)")

Dynamic order statistics

The second lab augments a red-black tree (the CLRS version, with sentinel nil) with subtree sizes. Only insertion is implemented, as needed for a cumulative median; deletion maintains tam by subtracting 1 along the path to the removed node and applying the same two lines at every rotation.

[ ]Red-black tree augmented with sizes: select and rankBrowser
ROJO, NEGRO = True, False

class Nodo:
    __slots__ = ("clave", "izq", "der", "padre", "color", "tam")
    def __init__(self, clave, nil):
        self.clave, self.izq, self.der, self.padre, self.color, self.tam = clave, nil, nil, nil, ROJO, 1

class ArbolEstadisticos:
    """Rojinegro (CLRS) aumentado con tam(x) = número de nodos del subárbol de x."""

    def __init__(self, mantener_tam_en_rotaciones=True):
        self.nil = Nodo(None, None)
        self.nil.izq = self.nil.der = self.nil.padre = self.nil
        self.nil.color, self.nil.tam = NEGRO, 0
        self.raiz = self.nil
        self.bien = mantener_tam_en_rotaciones

    def _rotar(self, x, lado):
        """lado = 'izq': y = x.der sube y x baja a su izquierda (y el simétrico)."""
        otro = "der" if lado == "izq" else "izq"
        y = getattr(x, otro)
        setattr(x, otro, getattr(y, lado))
        if getattr(y, lado) is not self.nil:
            getattr(y, lado).padre = x
        y.padre = x.padre
        if x.padre is self.nil:
            self.raiz = y
        elif x is x.padre.izq:
            x.padre.izq = y
        else:
            x.padre.der = y
        setattr(y, lado, x)
        x.padre = y
        if self.bien:                     # solo cambian los subárboles de x y de y: dos líneas
            y.tam = x.tam
            x.tam = x.izq.tam + x.der.tam + 1

    def insertar(self, clave):
        z = Nodo(clave, self.nil)
        y, x = self.nil, self.raiz
        while x is not self.nil:
            x.tam += 1                    # z quedará dentro del subárbol de x
            y = x
            x = x.izq if clave < x.clave else x.der
        z.padre = y
        if y is self.nil:
            self.raiz = z
        elif clave < y.clave:
            y.izq = z
        else:
            y.der = z
        self._arreglar(z)

    def _arreglar(self, z):
        while z.padre.color == ROJO:
            p, g = z.padre, z.padre.padre
            lado, otro = ("izq", "der") if p is g.izq else ("der", "izq")
            tio = getattr(g, otro)
            if tio.color == ROJO:         # caso 1: recolorear y subir
                p.color = tio.color = NEGRO
                g.color = ROJO
                z = g
            else:
                if z is getattr(p, otro): # caso 2: enderezar el zigzag
                    z = p
                    self._rotar(z, lado)
                z.padre.color = NEGRO     # caso 3: rotar el abuelo
                z.padre.padre.color = ROJO
                self._rotar(z.padre.padre, otro)
        self.raiz.color = NEGRO

    def seleccionar(self, i):
        """La clave de rango i (desde 1): se compara i con el tamaño del subárbol izquierdo más uno."""
        x = self.raiz
        while True:
            r = x.izq.tam + 1
            if i == r:
                return x.clave
            x, i = (x.izq, i) if i < r else (x.der, i - r)

    def rango(self, clave):
        """Número de claves estrictamente menores que la dada."""
        x, r = self.raiz, 0
        while x is not self.nil:
            if clave <= x.clave:
                x = x.izq
            else:
                r += x.izq.tam + 1
                x = x.der
        return r

    def comprobar(self):
        """Verifica las propiedades rojinegras y los tamaños; devuelve la altura negra."""
        def rec(x):
            if x is self.nil:
                return 1
            assert x.tam == x.izq.tam + x.der.tam + 1, "tamaño desactualizado"
            if x.color == ROJO:
                assert x.izq.color == NEGRO and x.der.color == NEGRO, "rojo con hijo rojo"
            hi, hd = rec(x.izq), rec(x.der)
            assert hi == hd, "alturas negras distintas"
            return hi + (x.color == NEGRO)
        assert self.raiz.color == NEGRO
        return rec(self.raiz)

    def altura(self):
        def h(x):
            return 0 if x is self.nil else 1 + max(h(x.izq), h(x.der))
        return h(self.raiz)

rng = np.random.default_rng(5)
claves = rng.permutation(20000).tolist()
arbol = ArbolEstadisticos()
for c in claves:
    arbol.insertar(c)
arbol.comprobar()
orden = sorted(claves)
assert all(arbol.seleccionar(int(i) + 1) == orden[i] for i in rng.integers(0, 20000, size=2000))
assert all(arbol.rango(int(c)) == int(c) for c in rng.integers(0, 20000, size=2000))
print(f"20000 claves: altura {arbol.altura()} (cota 2 log2(n+1) = {2 * math.log2(20001):.1f}); select y rank correctos")

roto = ArbolEstadisticos(mantener_tam_en_rotaciones=False)
for c in claves[:200]:
    roto.insertar(c)
orden = sorted(claves[:200])
malas = sum(roto.seleccionar(i + 1) != orden[i] for i in range(200))
print(f"sin actualizar tam en las rotaciones: {malas} de 200 selects erróneos")
try:
    roto.comprobar()
except AssertionError as e:
    print("  y la comprobación lo detecta:", e)

And the comparison the design calls for: the moving median of a series (a random walk, like a price series) in windows of 101 values. With keys known beforehand, a Fenwick frequency tree over compressed keys performs each step with one insertion, one deletion and one kk-th search. The augmented red-black tree needs no prior knowledge of keys: it computes the cumulative median of observations as they arrive.

[ ]Moving median: Fenwick on compressed keys and augmented red-black treeBrowser
def mediana_movil(x, w):
    """Mediana inferior de cada ventana x[i - w + 1 .. i] con un Fenwick de frecuencias sobre claves comprimidas."""
    valores = sorted(set(x))                          # compresión: clave -> rango 1..m
    pos = {v: i + 1 for i, v in enumerate(valores)}
    f = Fenwick(len(valores))
    out = []
    for i, v in enumerate(x):
        f.sumar(pos[v], 1)
        if i >= w:
            f.sumar(pos[x[i - w]], -1)                # sale el más antiguo de la ventana
        if i >= w - 1:
            out.append(valores[f.kesimo((w + 1) // 2) - 1])
    return out

rng = np.random.default_rng(6)
x = np.round(np.cumsum(rng.normal(size=20000)), 2).tolist()
w = 101
med = mediana_movil(x, w)
ref = np.median(np.lib.stride_tricks.sliding_window_view(np.array(x), w), axis=1)
print(f"{len(med)} ventanas de {w}: coincide con np.median en todas:", np.allclose(med, ref))

arbol = ArbolEstadisticos()
medianas = []
for i, v in enumerate(x[:5000]):
    arbol.insertar(v)
    medianas.append(arbol.seleccionar((i + 2) // 2))  # mediana inferior de los i + 1 vistos
ref_acum = [sorted(x[:i + 1])[(i + 2) // 2 - 1] for i in range(0, 5000, 499)]
print("mediana acumulada con el rojinegro, coincide en las 11 comprobaciones:", medianas[::499] == ref_acum)

Finally, two-dimensional Barnes-Hut with 4000 bodies, compared with exact force (computed with NumPy in Θ(n)\Theta(n) per body) for 100 random bodies:

[ ]Barnes-Hut: accuracy versus interactionsBrowser
class Celda:
    __slots__ = ("x0", "y0", "s", "idx", "hijos", "m", "cx", "cy")

def construir(P, x0, y0, s, idx, cap=8, prof=0):
    c = Celda()
    c.x0, c.y0, c.s, c.idx, c.hijos = x0, y0, s, idx, None
    c.m = len(idx)
    if c.m:
        c.cx, c.cy = P[idx, 0].mean(), P[idx, 1].mean()   # el agregado: masa y centro de masas
    if c.m > cap and prof < 30:
        h = s / 2
        der = P[idx, 0] >= x0 + h
        arr = P[idx, 1] >= y0 + h
        c.hijos = [construir(P, x0 + h * dx, y0 + h * dy, h, idx[(der == dx) & (arr == dy)], cap, prof + 1)
                   for dy in (0, 1) for dx in (0, 1)]
    return c

EPS2 = 1e-4                                               # suavizado: evita la singularidad a distancia 0

def fuerza_bh(c, p, P, i, theta):
    """Fuerza gravitatoria 2D suavizada sobre el punto i, y número de interacciones usadas."""
    if c.m == 0:
        return 0.0, 0.0, 0
    dentro = c.x0 <= p[0] < c.x0 + c.s and c.y0 <= p[1] < c.y0 + c.s
    if c.hijos is None:                                   # hoja: interacción directa con sus puntos
        q = P[c.idx[c.idx != i]]
        d = q - p
        r3 = (d[:, 0] ** 2 + d[:, 1] ** 2 + EPS2) ** 1.5
        return float((d[:, 0] / r3).sum()), float((d[:, 1] / r3).sum()), len(q)
    dx, dy = c.cx - p[0], c.cy - p[1]
    if not dentro and c.s < theta * math.hypot(dx, dy):   # lejos: una sola masa en el centro de masas
        r3 = (dx * dx + dy * dy + EPS2) ** 1.5
        return c.m * dx / r3, c.m * dy / r3, 1
    fx = fy = 0.0; k = 0
    for h in c.hijos:
        a, b, kk = fuerza_bh(h, p, P, i, theta)
        fx += a; fy += b; k += kk
    return fx, fy, k

rng = np.random.default_rng(7)
n = 4000
P = np.vstack([rng.normal([0.3, 0.6], 0.08, size=(n // 2, 2)), rng.normal([0.7, 0.3], 0.05, size=(n // 4, 2)),
               rng.random((n - n // 2 - n // 4, 2))]).clip(0, 0.999)
raiz = construir(P, 0.0, 0.0, 1.0, np.arange(n))
obj = rng.choice(n, size=100, replace=False)
D = P[None, :, :] - P[obj][:, None, :]
R3 = (D[..., 0] ** 2 + D[..., 1] ** 2 + EPS2) ** 1.5
exacta = np.stack([(D[..., 0] / R3).sum(1), (D[..., 1] / R3).sum(1)], axis=1)   # el término consigo mismo vale 0
for theta in (0.3, 0.5, 0.8, 1.2):
    res = [fuerza_bh(raiz, P[i], P, i, theta) for i in obj]
    F = np.array([(a, b) for a, b, _ in res])
    err = np.linalg.norm(F - exacta, axis=1) / np.linalg.norm(exacta, axis=1)
    print(f"theta = {theta}: {np.mean([k for *_, k in res]):6.0f} interacciones de media (exacto: {n - 1}), "
          f"error relativo mediano {np.median(err):.1e}")

With θ=0.5\theta = 0.5 each body uses about 400 interactions instead of 3999, with median error around 1%; with θ=0.3\theta = 0.3, about 950 and error 3.6×10−33.6 \times 10^{-3}. If you repeat the experiment with 2000, 8000 or 16,000 bodies (changing n), mean interactions per body with θ=0.5\theta = 0.5 barely move from 390 (the bound’s log⁡n\log n factor is not noticeable at these sizes), while exact calculation needs n−1n - 1: that is the difference between nearly linear and quadratic total cost.

The professional version

Python’s standard library includes neither a Fenwick nor a segment tree: in pure Python they are written as above, and when performance matters one vectorizes the static case with NumPy or uses other libraries’ structures.

NeedTool
Prefix sums, integral imagenp.cumsum (by axis), itertools.accumulate
Fixed-segment aggregatesnp.add.reduceat, np.minimum.reduceat
Sliding windowspandas.Series.rolling, numpy.lib.stride_tricks.sliding_window_view
Ordered set with rank and selectsortedcontainers.SortedList (blocked lists, not a tree)
Spatial ranges and neighborsscipy.spatial.cKDTree, sklearn.neighbors.KDTree and BallTree
Barnes-Hut in t-SNEsklearn.manifold.TSNE(method="barnes_hut", angle=0.5)
C++AtCoder Library lazy_segtree and fenwick_tree; __gnu_pbds::tree with order statistics
[ ]Libraries for static and spatial casesBrowser
import pandas as pd
from scipy.spatial import cKDTree

a = np.arange(1, 11)
print("cumsum:", np.cumsum(a))
cortes = [0, 3, 7]
print("reduceat, sumas de [0,3), [3,7), [7,10):", np.add.reduceat(a, cortes), "  mínimos al revés:", np.minimum.reduceat(a[::-1], cortes))
s = pd.Series(x[:12])
print("máximo móvil de 4 (pandas):", s.rolling(4).max().tolist()[3:8])
arbol_kd = cKDTree(P)
cuenta = len(arbol_kd.query_ball_point([0.3, 0.6], r=0.05))
print("puntos a distancia < 0.05 de (0.3, 0.6):", cuenta, "  fuerza bruta:", int((np.hypot(*(P - [0.3, 0.6]).T) < 0.05).sum()))

AtCoder Library’s lazy_segtree has exactly the interface of our generic class (op, e, mapping, composition, id), but is iterative: it stores the tree in an array of size 2⋅2⌈log⁡2n⌉2 \cdot 2^{\lceil \log_2 n \rceil} and traverses nodes bottom-up without recursion, making it several times faster. If you need old array versions (what was the minimum of [l,r][l, r] a thousand updates ago?), a segment tree supports path copying and becomes a persistent structure with O(log⁡n)\bigO(\log n) new nodes per update.

Common mistakes

Exercises

QuizChoose the structure
You have a fixed array of 10610^6 prices and will receive 10710^7 queries for the maximum between positions ll and rr. There are no updates. Which structure answers fastest overall?
NumericThe index they share
In a Fenwick tree of size 16 (one-based indices), a prefix query through 13 visits one chain of indices and an update at position 5 visits another. Which index appears in both?
NumericHow many blocks are corrected?
In a Fenwick tree of size n=16n = 16, how many tt indices does an update at position 5 modify?
NumericA rectangle with four reads
In a matrix's 2D prefix-sum table, S4,5=120S_{4,5} = 120, S1,5=30S_{1,5} = 30, S4,2=50S_{4,2} = 50 and S1,2=12S_{1,2} = 12. What is the sum of rows 2 to 4 and columns 3 to 5?
QuizDoes a sparse table work?
For which operations does a sparse table correctly answer arbitrary range queries in O(1)\bigO(1) using two overlapping windows?

More than one answer may be correct.

NumericSparse table size
How many entries in total are in the sparse table of an array of n=1000n = 1000 elements, with all levels kk such that 2k≤n2^k \le n and n−2k+1n - 2^k + 1 entries at level kk?
QuizCompose affine tags
In a sum segment tree with affine updates x↦αx+βx \mapsto \alpha x + \beta, a node has pending tag (α,β)=(2,1)(\alpha, \beta) = (2, 1) and receives an ‘assign 4’ update, namely (0,4)(0, 4). Which tag should remain pending?
QuizCan it be deferred?
For which of these (aggregate, range update) pairs does lazy propagation work with the stated tag and aggregate, without storing anything else in nodes?

More than one answer may be correct.

QuizWhat can be augmented?
Which fields can be maintained at every node of a red-black tree with insertions and deletions in O(log⁡n)\bigO(\log n), according to the augmentation theorem?

More than one answer may be correct.

ProofA query visits O(log n) nodes
Prove: In a segment tree over nn leaves, a query of range [l,r][l, r] visits at most four nodes per level, and at most two are only partially covered. In total it visits O(log⁡n)\bigO(\log n) nodes.
0
Call a visited node partial when its interval intersects [l,r][l, r] without being contained in it. Disjoint and contained nodes have no visited children.

Step 1 of 4. What must a partial node satisfy?

ProofThe LCA is the minimum between first occurrences
Prove: Let EE be the Euler tour of a rooted tree, let uu and vv be nodes with i=primera⁡(u)≤j=primera⁡(v)i = \operatorname{primera}(u) \le j = \operatorname{primera}(v) and let w=lca⁡(u,v)w = \operatorname{lca}(u, v). Then ww appears in E[i..j]E[i..j] and is the unique minimum-depth node in that segment.
0
Use the parenthesis structure of depth-first traversal: the segment of EE between the first and last occurrence of a node xx contains exactly the nodes in xx's subtree.

Step 1 of 3. Why does ww appear in E[i..j]E[i..j]?

CodeRange addition, range maximum
Implement class SegSumarMaximo(a) over a list a of integers, with methods sumar(l, r, v), which adds v to all elements at positions l..r (inclusive, zero-based), and maximo(l, r), which returns the maximum of positions l..r. Both must cost O(log⁡n)\bigO(\log n): a maximum segment tree with lazy addition tags. Tests compare against a naive version on random sequences with sizes that are not powers of two.
class SegSumarMaximo:
  def __init__(self, a):
      self.n = len(a)
      self.mx = [0] * (4 * self.n)     # máximo del intervalo de cada nodo
      self.tag = [0] * (4 * self.n)    # suma pendiente para los hijos
      # tu código: construir el árbol

  def sumar(self, l, r, v):
      # tu código
      pass

  def maximo(self, l, r):
      # tu código
      return 0
Shift+Enter to run

Summary

Key idea
Every range-query structure stores block aggregates and answers by combining a few: which blocks to store depends on the aggregate’s algebra (inverse, idempotence or only associativity) and whether data change.
  • With an inverse and fixed data, prefix sums: O(1)\bigO(1) per query in one or more dimensions, and the difference array for the inverse problem.
  • The Fenwick tree stores in tit_i block (i−lowbit⁡(i),i](i - \operatorname{lowbit}(i), i], with lowbit⁡(i)=i&(−i)\operatorname{lowbit}(i) = i \mathbin{\&} (-i). Queries remove the lowest set bit, updates add it and the kk-th is found by descending powers of two: all in O(log⁡n)\bigO(\log n) with one array.
  • A segment tree handles any monoid, commutative or not, because a query decomposes a range into O(log⁡n)\bigO(\log n) nodes with at most two partial nodes per level.
  • Lazy propagation defers range updates if they form a composition-closed family of monoid endomorphisms. Composition order (pending first, new second) is the most common source of errors.
  • With idempotent aggregates and fixed data, a sparse table answers in O(1)\bigO(1) after O(nlog⁡n)\bigO(n \log n), and block decomposition reduces preprocessing to linear.
  • LCA is an RMQ over Euler-tour depths, and general RMQ is an LCA in the Cartesian tree. Binary lifting is the simple O(log⁡n)\bigO(\log n) alternative.
  • An augmented balanced tree with fields depending only on children answers order statistics and interval overlaps with dynamic keys.
  • In space, quadtrees and octrees provide adaptive subdivision, cell pruning in queries and aggregation of distant cells in Barnes-Hut.