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 out of a total has depth at most . 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 .
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.
Let be natural-number weights with total . The tree built by recursive weighted-median splitting has the keys in order, and every key satisfies , so when . Building instead from the regularized weights gives a tree in which every key with satisfies both
Depth counts edges from the root, as Tree.depth. The uniform bound holds for every key, including those of weight zero.
The Lean statements
/-- 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 validModels.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.Definitionstheorem 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 positiveModels.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.Definitions/-- 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⟩Models.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.DefinitionsThe 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 , store for all . Then the sum over any half-open rectangle follows by inclusion and exclusion:
The table has entries for an matrix and is built row by row in time.
/-- Dense natural-number matrix, with zero outside its stored rectangle. -/abbrev Table := Array (Array Nat)def get (t : Table) (a b : Nat) : Nat := (t[a]?.getD #[])[b]?.getD 0/-- 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 jA Table is an array of rows of natural numbers. get t a b reads entry , and returns 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 .
/-- 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)/-- 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 prefix sums of one row. build f width height builds the table: its row 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.
/-- 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 , 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.
/-- 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 hbStructures.PrefixSum.DefinitionsTheorem (rectangle queries). For all and , the rectangle query on the built table is the sum of over .
/-- 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 hdStructures.PrefixSum.DefinitionsThe 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 with total , 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 , and so do the keys to its right. Recursing on both sides halves the weight at each level, so a key of weight is at depth at most . This is the classical guarantee of weight-balanced static trees.
/-- 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)/-- 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 . 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.
/-- 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)))/-- A static BST whose inorder ranks are the positions in the weight list. -/def build (weights : List Nat) : Tree := buildFuel weights.length weightsbuild 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 .
/-- 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⟩Models.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.DefinitionsTheorem (size, mass and depth). The tree has one node per weight. Every key satisfies ; hence, if , .
/-- All keys remain in their original inorder ranks, including zero weights. -/theorem size (weights : List Nat) : (build weights).size = weights.length := build_size weightsModels.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.Definitions/-- 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 validModels.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.Definitionstheorem 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 positiveModels.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.Definitionsmass 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 . When such keys can still be requested, as in the multiple-tree structure, the weights are first mixed with a uniform baseline.
/-- 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/-- 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 by , where is the number of keys and the original total. The new total is . Every new weight is at least , which is roughly a fraction of the new total, so every key gets logarithmic depth. And a key’s new weight is at least , roughly a fraction of the new total, so the frequency-based depth bound survives, within a factor of three in mass. The extra 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 and . For a key of positive weight, in logarithmic form, and .
/-- 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 weightsModels.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.Definitions/-- 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 validModels.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.Definitions/-- 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 validModels.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.Definitions/-- 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⟩Models.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.DefinitionsTheorem (pointer searches). In the pointer machine of Chapter 7, a search for a key of positive weight in the regularized tree, which walks down to and back to the root, leaves the tree unchanged and costs at most and at most .
/-- 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 positiveModels.Rotation, Models.Pointer.Machine, Bounds.StaticTree.Definitions, Structures.WeightedSearch.DefinitionsThe cost is that of Pointer.Serves: one unit for the request, plus one per pointer move, down to 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.