Binary Search Trees in Lean Check a result Declarations Bibliography Lean source

Chapter 34Prefix sums and weighted search trees

This chapter collects two small data structures that algorithms of Part IV use as building blocks.

  • Two-dimensional prefix sums answer a rectangle-sum query on a fixed matrix with four table reads. The optimal lazy-finger tree of Chapter 27 uses them to compute, in constant time, how many request transitions cross the boundary of a key interval.
  • Weighted search trees are static BSTs built by recursive weighted-median splitting, in which a key of weight wxw_x out of a total WW has depth at most log⁡2(W/wx)\log_2(W/w_x). The multiple-tree structure of Chapter 28 builds each of its local trees this way, from the successor frequencies of one key, mixed with a uniform baseline so that every key also has depth O(log⁡n)O(\log n).

Both are standard, and a reader who trusts them can skip this chapter: the theorems of Chapter 27 and Chapter 28 restate what they need. The chapter is here for the reader who checks a reading path, which goes through these definitions, or who wants to see the exact constants.

Main result
Weighted-median trees have entropy depth, even with a uniform baseline

Let w0,…,wn−1w_0, \dots, w_{n-1} be natural-number weights with total WW. The tree built by recursive weighted-median splitting has the keys 0,…,n−10, \dots, n-1 in order, and every key xx satisfies 2depth(x) wx≤W2^{\mathrm{depth}(x)}\, w_x \le W, so depth(x)≤log⁡2(W/wx)\mathrm{depth}(x) \le \log_2(W / w_x) when wx>0w_x > 0. Building instead from the regularized weights n wx+W+1n\,w_x + W + 1 gives a tree in which every key with wx>0w_x > 0 satisfies both

depth(x)  ≤  log⁡23Wwxanddepth(x)  ≤  log⁡2(2n).\mathrm{depth}(x) \;\le\; \log_2 \frac{3W}{w_x} \qquad\text{and}\qquad \mathrm{depth}(x) \;\le\; \log_2(2n).

Depth counts edges from the root, as Tree.depth. The uniform bound 2depth(x)≤2n2^{\mathrm{depth}(x)} \le 2n holds for every key, including those of weight zero.

The Lean statements
theoremWeightedSearch.Results.masspropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:19
/-- Exact integer form of the weighted search guarantee. -/theorem mass (weights : List Nat) (x : Nat) (valid : x < weights.length) :    2 ^ Tree.depth (build weights) x * weights[x] ≤ weights.sum := … build_mass weights x valid
theoremWeightedSearch.Results.depthpropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:23
theorem depth (weights : List Nat) (x : Nat) (valid : x < weights.length) (positive : 0 < weights[x]) :    (Tree.depth (build weights) x : ℝ) ≤ Real.logb 2 ((weights.sum : ℝ) / weights[x]) := …  build_depth weights x valid positive
theoremWeightedSearch.Results.balanced_depthpropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:41
/-- One tree simultaneously gives biased depth for positive-frequency keys anduniform logarithmic depth, with zero-frequency keys retained. -/theorem balanced_depth (weights : List Nat) (x : Nat) (valid : x < weights.length)    (positive : 0 < weights[x]) :    (Tree.depth (balancedBuild weights) x : ℝ) ≤ Real.logb 2 (3 * (weights.sum : ℝ) / weights[x]) ∧      (Tree.depth (balancedBuild weights) x : ℝ) ≤ Real.logb 2 (2 * weights.length) := …  ⟨balanced_depth_weighted weights x valid positive, balanced_depth_uniform weights x valid⟩
9 definitions in 2 chapters · reading list

The definitions are in Structures/PrefixSum/Definitions/Abstract.lean and Structures/WeightedSearch/Definitions/Abstract.lean, the theorems in Structures/PrefixSum/Abstract.lean and Structures/WeightedSearch/Abstract.lean.

34.1 Two-dimensional prefix sums

Given a matrix ff, store P[a][b]=∑i<a∑j<bf(i,j)P[a][b] = \sum_{i < a} \sum_{j < b} f(i, j) for all a,ba, b. Then the sum over any half-open rectangle [a,b)×[c,d)[a, b) \times [c, d) follows by inclusion and exclusion:

∑i∈[a,b)∑j∈[c,d)f(i,j)  =  P[b][d]−P[a][d]−P[b][c]+P[a][c].\sum_{i \in [a,b)} \sum_{j \in [c,d)} f(i, j) \;=\; P[b][d] - P[a][d] - P[b][c] + P[a][c].

The table has (h+1)(w+1)(h + 1)(w + 1) entries for an h×wh \times w matrix and is built row by row in O(hw)O(hw) time.

defPrefixSum.Tableno axiomsStructures/PrefixSum/Definitions/Abstract.lean:8
/-- Dense natural-number matrix, with zero outside its stored rectangle. -/abbrev Table := Array (Array Nat)
defPrefixSum.getno axiomsStructures/PrefixSum/Definitions/Abstract.lean:11
def get (t : Table) (a b : Nat) : Nat := (t[a]?.getD #[])[b]?.getD 0
defPrefixSum.sumPrefixpropext · Classical.choice · Quot.soundStructures/PrefixSum/Definitions/Abstract.lean:13
/-- Mathematical prefix sum over a half-open rectangle from the origin. -/def sumPrefix (f : Nat → Nat → Nat) (a b : Nat) : Nat :=  ∑ i ∈ Finset.range a, ∑ j ∈ Finset.range b, f i j

A Table is an array of rows of natural numbers. get t a b reads entry (a,b)(a, b), and returns 00 outside the stored rows and columns, so reads are total. sumPrefix f a b is the mathematical quantity that the table is meant to store, the sum over [0,a)×[0,b)[0, a) \times [0, b).

defPrefixSum.rowno axiomsStructures/PrefixSum/Definitions/Abstract.lean:17
/-- Prefix sums of a single row, including the empty prefix. -/def row (f : Nat → Nat) : Nat → Array Nat  | 0 => #[0]  | n + 1 => let previous := row f n; previous.push (previous[n]?.getD 0 + f n)
defPrefixSum.buildpropextStructures/PrefixSum/Definitions/Abstract.lean:22
/-- Build two-dimensional prefixes by adding each row's horizontal prefixes tothose of all preceding rows. Width is fixed; the final argument is row count. -/def build (f : Nat → Nat → Nat) (width : Nat) : Nat → Table  | 0 => #[Array.replicate (width + 1) 0]  | height + 1 =>      let previous := build f width height      let horizontal := row (f height) width      previous.push (Array.ofFn fun b : Fin (width + 1) =>        get previous height b.val + horizontal[b.val]?.getD 0)

row f n is the array of the n+1n + 1 prefix sums 0,f(0),f(0)+f(1),…0, f(0), f(0) + f(1), \dots of one row. build f width height builds the (height+1)×(width+1)(\mathit{height} + 1) \times (\mathit{width} + 1) table: its row 00 is all zeros, and each further row adds the horizontal prefix sums of the next input row to the previous table row. The input is a function, not a matrix, so a caller can pass any way of reading its data; the optimizer of Chapter 27 passes get of its transition-count matrix.

defPrefixSum.rectangleno axiomsStructures/PrefixSum/Definitions/Abstract.lean:32
/-- Four cached prefix values answer a half-open rectangular sum query. Thepositive terms are added before subtracting, avoiding truncated intermediates. -/def rectangle (t : Table) (a b c d : Nat) : Nat :=  get t b d + get t a c - (get t a d + get t b c)

rectangle t a b c d is the inclusion–exclusion formula. Subtraction on natural numbers truncates at 00, so the definition adds the two positive terms before subtracting the two negative ones: since the true value is nonnegative, the result is exact whenever the table holds genuine prefix sums.

Theorem (prefix sums). Every stored entry, within the built rectangle, is the prefix sum it is meant to be.

theoremPrefixSum.Results.cached_prefixpropext · Classical.choice · Quot.soundStructures/PrefixSum/Abstract.lean:9
/-- Every cached prefix agrees with the defining rectangular sum. -/theorem cached_prefix (f : Nat → Nat → Nat) (width height a b : Nat)    (ha : a ≤ height) (hb : b ≤ width) :    get (build f width height) a b = sumPrefix f a b := build_get f width height a b ha hb

Theorem (rectangle queries). For all a≤b≤heighta \le b \le \mathit{height} and c≤d≤widthc \le d \le \mathit{width}, the rectangle query on the built table is the sum of ff over [a,b)×[c,d)[a, b) \times [c, d).

theoremPrefixSum.Results.rectangular_sumpropext · Classical.choice · Quot.soundStructures/PrefixSum/Abstract.lean:14
/-- Four cached values answer a rectangle query exactly, including emptyrectangles and rectangles touching any edge of the stored matrix. -/theorem rectangular_sum (f : Nat → Nat → Nat) (width height a b c d : Nat)    (hab : a ≤ b) (hb : b ≤ height) (hcd : c ≤ d) (hd : d ≤ width) :    rectangle (build f width height) a b c d = ∑ i ∈ Finset.Ico a b, ∑ j ∈ Finset.Ico c d, f i j :=  rectangle_build f width height a b c d hab hb hcd hd

The rectangles may be empty or touch any edge of the matrix. This is what lets the optimizer’s toll, a sum of four such rectangles around a key interval, be exact for every interval, including those at the ends of the universe.

34.2 Weighted search trees

Given weights w0,…,wn−1w_0, \dots, w_{n-1} with total WW, put at the root the weighted median: the key in which the cumulative weight reaches half of the total. The keys to its left then have total weight at most W/2W/2, and so do the keys to its right. Recursing on both sides halves the weight at each level, so a key of weight wxw_x is at depth at most log⁡2(W/wx)\log_2(W/w_x). This is the classical guarantee of weight-balanced static trees.

defWeightedSearch.locateno axiomsStructures/WeightedSearch/Definitions/Abstract.lean:8
/-- Locate the key containing a given unit of cumulative integer weight.Zero-weight keys are skipped. The specification requires `target < sum`. -/def locate : List Nat → Nat → Nat  | [], _ => 0  | w :: ws, target => if target < w then 0 else 1 + locate ws (target - w)
defWeightedSearch.pivotno axiomsStructures/WeightedSearch/Definitions/Abstract.lean:14
/-- Select a weighted median. An all-zero interval selects its first key;positive-weight depth guarantees do not depend on this tie convention. -/def pivot (weights : List Nat) : Nat :=  if weights.sum = 0 then 0 else locate weights (weights.sum / 2)

Weights are lists of natural numbers, and positions in the list are the key ranks. locate ws target returns the position of the key whose block of weight contains unit number target, when the weights are laid end to end; keys of weight zero have empty blocks and are skipped. pivot ws locates unit ⌊W/2⌋\lfloor W/2 \rfloor. When all weights are zero there is no such unit, and pivot takes the first key; the depth bounds below concern keys of positive weight and do not depend on this choice.

defWeightedSearch.buildFuelno axiomsStructures/WeightedSearch/Definitions/Abstract.lean:19
/-- Weighted-median recursion with explicit fuel. `build` supplies enough fuelto retain every key, including keys of weight zero. -/def buildFuel : Nat → List Nat → Tree  | 0, _ => .nil  | _ + 1, [] => .nil  | fuel + 1, w :: ws =>      let weights := w :: ws      let p := pivot weights      .node (buildFuel fuel (weights.take p)) (buildFuel fuel (weights.drop (p + 1)))
defWeightedSearch.buildno axiomsStructures/WeightedSearch/Definitions/Abstract.lean:29
/-- A static BST whose inorder ranks are the positions in the weight list. -/def build (weights : List Nat) : Tree := buildFuel weights.length weights

build ws puts the pivot at the root, then builds the left subtree from the weights before the pivot and the right subtree from those after it. The recursion is on a fuel argument, so that Lean accepts it as terminating; build supplies the list’s length, which is enough to place every key, including keys of weight zero. The result is a Tree, a shape whose inorder ranks are the positions in the list.

Theorem (weighted median). For a nonempty weight list, the pivot is a valid position, and the weights strictly before it and strictly after it each total at most half of WW.

theoremWeightedSearch.Results.medianpropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:9
/-- Weighted-median selection leaves at most half of the mass in either child. -/theorem median (weights : List Nat) (nonempty : weights ≠ []) :    pivot weights < weights.length ∧      2 * (weights.take (pivot weights)).sum ≤ weights.sum ∧      2 * (weights.drop (pivot weights + 1)).sum ≤ weights.sum :=  ⟨pivot_lt weights nonempty, pivot_halves weights⟩

Theorem (size, mass and depth). The tree has one node per weight. Every key xx satisfies 2depth(x)wx≤W2^{\mathrm{depth}(x)} w_x \le W; hence, if wx>0w_x > 0, depth(x)≤log⁡2(W/wx)\mathrm{depth}(x) \le \log_2(W/w_x).

theoremWeightedSearch.Results.sizepropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:16
/-- All keys remain in their original inorder ranks, including zero weights. -/theorem size (weights : List Nat) : (build weights).size = weights.length := build_size weights
theoremWeightedSearch.Results.masspropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:19
/-- Exact integer form of the weighted search guarantee. -/theorem mass (weights : List Nat) (x : Nat) (valid : x < weights.length) :    2 ^ Tree.depth (build weights) x * weights[x] ≤ weights.sum := build_mass weights x valid
theoremWeightedSearch.Results.depthpropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:23
theorem depth (weights : List Nat) (x : Nat) (valid : x < weights.length) (positive : 0 < weights[x]) :    (Tree.depth (build weights) x : ℝ) ≤ Real.logb 2 ((weights.sum : ℝ) / weights[x]) :=  build_depth weights x valid positive

mass is the exact integer statement, with no logarithm and no case split; it holds trivially for keys of weight zero. depth is the logarithmic form, in which depth is Tree.depth, the number of edges from the root.

34.2.1 A uniform baseline

Built from observed frequencies, a weighted tree can put an unobserved key, of weight zero, arbitrarily deep, up to depth n−1n - 1. When such keys can still be requested, as in the multiple-tree structure, the weights are first mixed with a uniform baseline.

defWeightedSearch.regularizeno axiomsStructures/WeightedSearch/Definitions/Abstract.lean:32
/-- Add a uniform baseline to the weighted frequencies. The extra unit makesall entries positive even when the entire observed row is zero. -/def regularize (weights : List Nat) : List Nat :=  weights.map fun w => weights.length * w + weights.sum + 1
defWeightedSearch.balancedBuildno axiomsStructures/WeightedSearch/Definitions/Abstract.lean:37
/-- A frequency-biased tree with logarithmic worst-case depth for every key,including those not yet observed. -/def balancedBuild (weights : List Nat) : Tree := build (regularize weights)

regularize replaces each weight wxw_x by n wx+W+1n\,w_x + W + 1, where nn is the number of keys and WW the original total. The new total is n(2W+1)n(2W + 1). Every new weight is at least W+1W + 1, which is roughly a 1/(2n)1/(2n) fraction of the new total, so every key gets logarithmic depth. And a key’s new weight is at least n wxn\,w_x, roughly a wx/(2W)w_x / (2W) fraction of the new total, so the frequency-based depth bound survives, within a factor of three in mass. The extra +1+1 keeps every weight positive, even when all original weights are zero. balancedBuild is build on the regularized weights.

Theorem (regularized trees). The regularized tree has one node per weight. Every key satisfies 2depth(x)≤2n2^{\mathrm{depth}(x)} \le 2n and 2depth(x)wx≤3W2^{\mathrm{depth}(x)} w_x \le 3W. For a key of positive weight, in logarithmic form, depth(x)≤log⁡2(3W/wx)\mathrm{depth}(x) \le \log_2(3W/w_x) and depth(x)≤log⁡2(2n)\mathrm{depth}(x) \le \log_2(2n).

theoremWeightedSearch.Results.balanced_sizepropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:27
/-- Adding a uniform baseline preserves the size of the represented universe. -/theorem balanced_size (weights : List Nat) : (balancedBuild weights).size = weights.length :=  WeightedSearch.balanced_size weights
theoremWeightedSearch.Results.balanced_capacitypropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:31
/-- Every key in the regularized tree has logarithmic worst-case depth. -/theorem balanced_capacity (weights : List Nat) (x : Nat) (valid : x < weights.length) :    2 ^ Tree.depth (balancedBuild weights) x ≤ 2 * weights.length :=  WeightedSearch.balanced_capacity weights x valid
theoremWeightedSearch.Results.balanced_masspropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:36
/-- The frequency-biased guarantee is retained within factor three in mass. -/theorem balanced_mass (weights : List Nat) (x : Nat) (valid : x < weights.length) :    2 ^ Tree.depth (balancedBuild weights) x * weights[x] ≤ 3 * weights.sum :=  WeightedSearch.balanced_mass weights x valid
theoremWeightedSearch.Results.balanced_depthpropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:41
/-- One tree simultaneously gives biased depth for positive-frequency keys anduniform logarithmic depth, with zero-frequency keys retained. -/theorem balanced_depth (weights : List Nat) (x : Nat) (valid : x < weights.length)    (positive : 0 < weights[x]) :    (Tree.depth (balancedBuild weights) x : ℝ) ≤ Real.logb 2 (3 * (weights.sum : ℝ) / weights[x]) ∧      (Tree.depth (balancedBuild weights) x : ℝ) ≤ Real.logb 2 (2 * weights.length) :=  ⟨balanced_depth_weighted weights x valid positive, balanced_depth_uniform weights x valid⟩

Theorem (pointer searches). In the pointer machine of Chapter 7, a search for a key xx of positive weight in the regularized tree, which walks down to xx and back to the root, leaves the tree unchanged and costs at most 1+2log⁡2(3W/wx)1 + 2\log_2(3W/w_x) and at most 1+2log⁡2(2n)1 + 2\log_2(2n).

theoremWeightedSearch.Results.querypropext · Classical.choice · Quot.soundStructures/WeightedSearch/Abstract.lean:49
/-- Physical pointer searches realize both bounds, charging the outward path,return path, and request unit. This is a query guarantee, not a preprocessingruntime theorem. -/theorem query (weights : List Nat) (x : Nat) (valid : x < weights.length) (positive : 0 < weights[x]) :    ∃ k, Pointer.Serves (balancedBuild weights) (balancedBuild weights) x k ∧      (k : ℝ) ≤ 1 + 2 * Real.logb 2 (3 * (weights.sum : ℝ) / weights[x]) ∧      (k : ℝ) ≤ 1 + 2 * Real.logb 2 (2 * weights.length) := balanced_query weights x valid positive

The cost is that of Pointer.Serves: one unit for the request, plus one per pointer move, down to xx and back up, since the next search there starts at the root again. This is a statement about the queries only; no theorem bounds the time to build the tree. The multiple-tree structure of Chapter 28 does not use this theorem: it searches its local trees in the linked-search model of Chapter 11, with its own lookup. It relies on the depth bounds above, for regularized trees whose nodes are labelled with actual keys by Tree.labelWith.