# Order-Statistic B+ Trees for Block-Structured Documents

December 2, 2026 • 12 min read • Data Structures, Rich Text Editors

A rich-text editor asks two questions all the time: which block contains position *N*, and where does this block start? Selection, formatting, rendering, comments and collaboration all go through them, often several times per keystroke.

Most editors answer both with a loop over the list of blocks. That is fine for a short document and slow for a long one. This article looks at how that loop works, what an index for it has to do, and how an order-statistic B+ tree answers both questions in O(log n) without becoming a second source of truth.

The examples use Quill’s [Parchment](https://github.com/quilljs/parchment), because its source is short and easy to read. Nothing here is specific to Quill: the same idea works for any editor that stores a document as a list of blocks.

This is part one of two. Part two is about virtualization, where an index like this becomes a requirement.

## How editors find a position today

The way an editor maps an index to a block decides how much every positional read costs. This section looks at how Parchment does it.

Parchment stores a document as a tree of blots. The root is a `Scroll`, and its children are lines: a `Block` for a paragraph, heading or list item, a `BlockEmbed` for a table or an image, a `Container` for nested structures. Each child knows its `length()`, and blocks cache it.

The children live in a doubly linked list. To find the block that contains an index, Parchment starts at the head and subtracts lengths until the remainder fits:

```ts
// parchment/src/collection/linked-list.ts (trimmed)
public find(index: number): [T | null, number] {
  let cur = this.head;
  while (cur) {
    const length = cur.length();
    if (index < length) return [cur, index];
    index -= length;
    cur = cur.next;
  }
  return [null, 0];
}
```

[Diagram: A linked list of nine blocks. find(300) visits the first five, subtracting each length, and stops at the paragraph of length 260.]

**Figure 1.** `find(300)` over nine blocks (P paragraph, H heading, L list, T table). The numbers above are the remaining index on arrival, the numbers below are where each block starts. It takes five steps to reach `P · 260`.

The reverse question, where a block starts, is the same walk. A blot asks its parent for its offset among its siblings and adds the parent’s own offset:

```ts
// parchment/src/blot/abstract/shadow.ts
public offset(root: Blot = this.parent): number {
  if (this.parent == null || this === root) return 0;
  return this.parent.children.offset(this) + this.parent.offset(root);
}
```

Editors with an array-based model have the same problem: scanning an array of sizes is still linear, just friendlier to the CPU cache. ProseMirror, for example, keeps a small cache of recently resolved positions to soften it.

Let’s write this down more precisely. Say the document is a sequence of blocks $u_1, \dots, u_n$ with lengths $w_1, \dots, w_n$, and $W_j$ is the sum of the first $j$ lengths:

$$
W_j = \sum_{t=1}^{j} w_t \qquad W_0 = 0
$$

Then the two questions are:

$$
\operatorname{select}(i) = \min\{\, j : W_j > i \,\} \qquad \operatorname{rank}(u_j) = W_{j-1}
$$

A linked list answers both by walking from the head, so the cost grows with $j$. If every character is equally likely to be queried, block $j$ is hit with probability $w_j / W_n$, and the average walk is about half of the document:

$$
\mathbb{E}\left[T_{\text{list}}\right] = \sum_{j=1}^{n} j \cdot \frac{w_j}{W_n} \;\approx\; \frac{n+1}{2} \quad \text{when lengths are similar}
$$

On a document with 10,000 blocks that is about 5,000 steps per read. A single keystroke usually does several reads: the selection is clamped to the document length, converted from a DOM range to an index, converted back for rendering, and asked for its formats. If one keystroke does $r$ reads:

$$
C_{\text{keystroke}} \approx r \cdot \frac{n}{2} \qquad r = 4,\ n = 10^4 \;\Rightarrow\; 2 \times 10^4 \ \text{steps}
$$

That is 20,000 steps before the browser can paint, and each step touches an object the CPU has not seen since the previous keystroke.

## What an index has to do

Before choosing a data structure, it helps to write down exactly what it must support. Without the editor around it, this is a well-known problem called dynamic partial sums. We need five operations over a sequence of blocks with lengths:

-   `select(i)`: the block that contains index *i*, and where it starts.
-   `rank(block)`: where a block starts.
-   `update(block, delta)`: a block’s length changes. This is typing.
-   `insert` and `delete`: Enter, Backspace across a line break, paste.

Research on this problem shows that $\Theta(\log n)$ per operation is the best any structure can do. So the goal is not to beat the logarithm. The goal is to get small constants and to make the index safe to run inside an editor, which adds a few requirements of its own:

1.  **No keys.** A block’s position is the sum of the lengths before it, so it cannot be stored as a key.
2.  **Lookups from a block.** The editor holds a block object and asks where it starts.
3.  **Inserts anywhere.** Inserting in the middle of the document is the normal case.
4.  **Cheap length updates.** Typing changes one block’s length per keystroke.
5.  **More than one aggregate.** Length today; line counts, block ids and pixel heights later.
6.  **Only a cache.** The editor’s own list stays the source of truth. The index can be thrown away and rebuilt at any time.

The last requirement rules out a rope or a piece table. Both are better document models, but adopting one means rewriting the editor. Here we want an index next to the existing model.

## Choosing the data structure

Several classic structures can answer positional queries. The table compares them against the requirements above.

| Candidate | select / rank | insert in the middle | Verdict |
| --- | --- | --- | --- |
| Prefix-sum array | O(log n) | O(n) | Every insert rewrites the rest of the array. |
| [Fenwick tree](https://en.wikipedia.org/wiki/Fenwick_tree) | O(log n) | O(n) | Great for updates, but positions are fixed, so an insert shifts everything after it. |
| Balanced binary tree (red-black, treap) with subtree sums | O(log n) | O(log n) | Correct and well known. One node per block, about 14 levels at 10,000 blocks, and rotations must repair the sums. |
| Skip list with widths | O(log n) expected | O(log n) expected | Works, but uses more pointers and randomness, and a second aggregate is awkward. |
| Finger tree | O(log n) | O(log n) | Elegant and persistent, but allocates a lot in mutable JavaScript. |
| **B+ tree with subtree sums** | O(B log<sub>B</sub> n) | O(B log<sub>B</sub> n) | **Shallow, arrays inside nodes, blocks in document order, local splits.** |

A B+ tree that stores sums instead of keys is sometimes called a [counted B-tree](https://www.chiark.greenend.org.uk/~sgtatham/algorithms/cbtree.html). The same idea is used in xi-editor’s rope, a B-tree with metrics, and VS Code’s piece tree uses a red-black tree where each node stores the length and line count of its left subtree.

### How tall the tree is

A B+ tree with fanout $B$ holds up to $B$ entries per node. When every node is full, the height is:

$$
h_{\min} = \left\lceil \log_B n \right\rceil
$$

After splits, nodes are only guaranteed to be half full, and the root can have just two children. So the realistic bound uses $B/2$:

$$
n \ge 2\left(\tfrac{B}{2}\right)^{h-1} \quad\Longrightarrow\quad h_{\max} \le 1 + \left\lfloor \log_{B/2} \tfrac{n}{2} \right\rfloor
$$

For $B = 32$ even a large document needs only a few levels:

| Blocks | Linked list, average steps | Height, full nodes | Height, half-full nodes | Binary tree height |
| --- | --- | --- | --- | --- |
| 100 | 50 | 2 | 2 | 7 |
| 1,000 | 500 | 2 | 3 | 10 |
| 10,000 | 5,000 | 3 | 4 | 14 |
| 100,000 | 50,000 | 4 | 4 | 17 |
| 1,000,000 | 500,000 | 4 | 5 | 20 |

### Why fanout 32

Each level of the tree costs one jump to a new node plus a scan of up to $B$ entries inside it. A bigger $B$ means fewer levels but longer scans. If a jump costs $c_{\text{hop}}$ and one scan step costs $c_{\text{scan}}$, a lookup costs:

$$
C(B) = \left(c_{\text{hop}} + B\,c_{\text{scan}}\right)\log_B n = \frac{c_{\text{hop}} + B\,c_{\text{scan}}}{\ln B}\,\ln n
$$

The $\ln n$ part does not depend on $B$, so only the fraction matters. Its minimum is where the derivative is zero:

$$
\frac{d}{dB}\,\frac{c_{\text{hop}} + B\,c_{\text{scan}}}{\ln B} = 0 \quad\Longrightarrow\quad B\left(\ln B - 1\right) = \frac{c_{\text{hop}}}{c_{\text{scan}}}
$$

Jumping to a node the CPU has not touched recently is much more expensive than scanning a few numbers it just loaded. If a jump costs about 80 scan steps, the optimum lands on 32. The curve is flat around it, so anything from 16 to 64 works, and 32 is a good default.

[Diagram: Log-log chart. Linked-list steps grow linearly with document size; B+ tree comparisons step from 32 to 128. They cross at about 128 blocks; at 10,000 blocks it is 5,000 steps against at most 96 comparisons.]

**Figure 2.** Average blocks visited by the linked-list loop ($n/2$) against the worst case for a fanout-32 tree ($B \cdot \lceil \log_B n \rceil$). Below about 128 blocks the loop is cheaper, so small documents should not use the tree. At 10,000 blocks it is 5,000 steps against at most 96 comparisons.

## The data structure

The main idea is simple: every node stores the sum of its subtree, and nothing stores a key. Leaves hold blocks in document order, internal nodes hold child nodes, and a block’s position is whatever the sums to its left add up to.

```ts
interface Summary { length: number; units: number; }

interface Leaf {
  kind: 'leaf';
  parent: Internal | null;
  units: Unit[];           // at most B blocks, in document order
  lengths: number[];       // the length of each block, same order
  sum: Summary;
}

interface Internal {
  kind: 'internal';
  parent: Internal | null;
  children: Node[];        // at most B child nodes
  sum: Summary;            // the sum of the children's sums
}

// The editor owns the blocks, so a WeakMap never keeps a deleted block alive.
const leafOf = new WeakMap<Unit, Leaf>();
```

### Finding a block by index

`select` works like the linked-list loop, but it skips whole subtrees instead of single blocks. Here is the same document as Figure 1, under a tree small enough to draw:

[Diagram: A two-level tree with root length 1370. select(300) skips leaf A (length 154), enters leaf B with 146 remaining, and stops at P 260.]

**Figure 3.** `select(300)`. At the root, 300 is not below A's length of 154, so the whole of A is skipped and 146 is left. In leaf B, 146 is below the first block's 260, so the answer is `P · 260`, starting at 154. Three comparisons instead of five steps.

```ts
function select(root: Node, index: number): { unit: Unit; start: number } | null {
  if (index < 0 || index >= root.sum.length) return null;
  let node = root;
  let remaining = index;

  while (node.kind === 'internal') {
    let c = 0;
    while (remaining >= node.children[c].sum.length) {
      remaining -= node.children[c].sum.length; // skip the whole subtree
      c++;
    }
    node = node.children[c];
  }

  let u = 0;
  while (remaining >= node.lengths[u]) remaining -= node.lengths[u++];
  return { unit: node.units[u], start: index - remaining };
}
```

Each level scans at most $B$ entries, so:

$$
C_{\text{select}} \le B \cdot h \qquad n = 10^4:\ \ 32 \cdot 3 = 96 \ \ \text{vs.} \ \ \mathbb{E}\left[T_{\text{list}}\right] \approx 5{,}000
$$

### Finding where a block starts

`rank` goes the other way. It finds the block’s leaf through `leafOf`, then walks up to the root and adds everything to the left on each level:

$$
\operatorname{rank}(u) = \sum_{\ell=0}^{h-1}\ \sum_{s \,\in\, \operatorname{left}_\ell(u)} \operatorname{length}(s)
$$

[Diagram: rank of P 640: inside leaf B the two blocks to its left add 261; at the root, leaf A adds 154; the result is 415.]

**Figure 4.** `rank(P · 640)`. Inside leaf B, the two blocks to its left add 261. At the root, leaf A adds 154. The block starts at 415, the same answer the linked list gets after walking past six blocks.

```ts
function rank(unit: Unit): number | null {
  const leaf = leafOf.get(unit);
  if (!leaf) return null;

  let start = 0;
  const at = leaf.units.indexOf(unit);
  for (let i = 0; i < at; i++) start += leaf.lengths[i];

  let child: Node = leaf;
  for (let parent = leaf.parent; parent; child = parent, parent = parent.parent) {
    for (const sibling of parent.children) {
      if (sibling === child) break;
      start += sibling.sum.length;  // everything left of us on this level
    }
  }
  return start;
}
```

### Updating a length

With sums in the nodes, typing is the cheapest operation. A length change walks up the parent chain and adds the delta to each sum on the way:

```ts
function update(unit: Unit, delta: number): void {
  const leaf = leafOf.get(unit)!;
  leaf.lengths[leaf.units.indexOf(unit)] += delta;
  for (let node: Node | null = leaf; node; node = node.parent) {
    node.sum.length += delta;   // no re-summing, just carry the delta up
  }
}
```

A node could also store prefix sums of its children instead of plain sums. That makes `select` a binary search inside each node, but every update then has to shift all the later entries. The table shows the trade-off:

| Node stores | select, per level | update, per level |
| --- | --- | --- |
| Child sums | linear scan of up to B entries | add the delta to one entry |
| Child prefix sums | binary search | shift every later entry |

With prefix sums the binary search takes $\log_2 B \cdot \log_B n = \log_2 n$ comparisons, the same as a binary tree, but with far fewer jumps. A keystroke is one update and $r$ reads, so the cost per keystroke is:

$$
\begin{aligned} C_{\text{sums}} &\approx r\,h\left(c_{\text{hop}} + B\,c_{\text{scan}}\right) + h\,c_{\text{hop}} \\ C_{\text{prefix}} &\approx r\,h\left(c_{\text{hop}} + c_{\text{cmp}}\log_2 B\right) + h\left(c_{\text{hop}} + B\,c_{\text{scan}}\right) \end{aligned}
$$

On paper prefix sums win when a keystroke does two or more reads. In practice a linear scan over 32 numbers is fast and predictable, and both options are small next to the jump between nodes. I’d start with plain sums, because the update path stays trivial, and switch only after profiling.

## Storing more than length

Length is only the first thing an editor wants to look up. The same tree can answer other positional questions, as long as each value can be added up from children to parents.

Formally, the summary has to be a monoid $(M, \oplus, e)$: it combines associatively and has an empty value. A node’s summary is then the combination of its children:

$$
\operatorname{sum}(\text{node}) = \operatorname{sum}(c_1) \oplus \operatorname{sum}(c_2) \oplus \cdots \oplus \operatorname{sum}(c_k)
$$

In practice it means a node can carry several values at once, and each of them gets its own `select` for free. Selecting by pixel height, for example, answers “which block is at y = 48,000 px?” without asking the DOM. That matters a lot once part of the document is not rendered at all.

```ts
interface Summary {
  length: number;          // characters
  lines: number;           // a table counts as several lines
  height: number | null;   // null: some block below hasn't been laid out yet
}

const EMPTY: Summary = { length: 0, lines: 0, height: 0 };

function combine(a: Summary, b: Summary): Summary {
  return {
    length: a.length + b.length,
    lines: a.lines + b.lines,
    // An unknown height makes the whole sum unknown instead of silently wrong.
    height: a.height === null || b.height === null ? null : a.height + b.height,
  };
}
```

The `null` case matters. Some heights are unknown until a block has been laid out. Counting them as zero would give a confident but wrong pixel offset and scroll the reader to the wrong paragraph. In monoid terms, `null` is an absorbing element $\bot$:

$$
x \oplus \bot = \bot \oplus x = \bot \qquad x \oplus y = x + y \quad \text{for } x, y \in \mathbb{R}_{\ge 0}
$$

The sum stays associative and 0 is still the empty value. If the root height is $\bot$, the query returns “unknown” and the caller falls back to another way.

Lookup by a stable block id is not a sum, so it lives in a separate map from id to block. It has one rule: when a line splits, an id can move from one block to another in the same batch of changes. If one block’s old ids are released after another block claimed them, the map loses the entry. So release all old ids first, then claim the new ones:

```ts
for (const change of batch) {
  for (const id of change.oldIds) if (idMap.get(id) === change.unit) idMap.delete(id);
}
for (const change of batch) {
  for (const id of change.newIds) idMap.set(id, change.unit);
}
```

## Keeping the index in sync

An index is only useful if it stays in sync with the document. This section covers how the tree learns about changes: lazily for lengths, immediately for structure.

### Lazy length updates

`update` above assumes we know the delta. Editors often don’t: a mutation resets a block’s cached length without saying by how much. Measuring a block after every mutation would give back much of what the faster reads won.

So the tree is lazy. A mutation only puts the block into a dirty set. The next read measures each dirty block once and fixes the sums on its path:

```ts
const dirty = new Set<Unit>();

// Called from the editor's mutation hooks: cheap, no measuring.
function markDirty(unit: Unit): void {
  dirty.add(unit);
}

// Called at the start of every indexed read.
function flush(): void {
  for (const unit of dirty) {
    const leaf = leafOf.get(unit);
    if (!leaf) continue;  // removed since it was marked
    const delta = unit.length() - leaf.lengths[leaf.units.indexOf(unit)];
    if (delta !== 0) update(unit, delta);
  }
  dirty.clear();
}
```

If $m$ mutations touch $k$ different blocks between two reads, the two approaches cost:

$$
C_{\text{eager}} = m\left(c_{\text{measure}} + h\,c_{\text{hop}}\right) \qquad C_{\text{lazy}} = m\,c_{\text{mark}} + k\left(c_{\text{measure}} + h\,c_{\text{hop}}\right), \quad k \le m
$$

Typing is the best case for this. A transaction that inserts, formats and normalizes the same line touches it many times, so $m$ is large and $k = 1$.

[Diagram: Typing abc into P 260 marks it dirty. On the next read its length becomes 263, and +3 is added to leaf B and the root.]

**Figure 5.** Typing "abc" into `P · 260` only adds it to the dirty set. The next read measures it once and adds +3 to every sum on its path.

### Where to hook in

Most editors normalize their tree after a transaction: they merge adjacent text nodes, fix containers and so on. It is tempting to sync the index when normalization finishes, but that is too late. Normalization is usually deferred while a batch of changes is open, and the editor still reads its own length between the operations of that batch. Hook the index to mutations instead:

[Diagram: Sequence diagram. A transaction begins a batch on the document root. For every operation: the transaction sends insert, delete or format; the document root reads its own length, which must be correct at that point; it mutates the block; the block marks itself dirty in the index; normalize() is deferred because the batch is open. Finally the transaction ends the batch and normalize() runs.]

**Figure 6.** Inside a batch, normalization doesn't run, but positions are still read. An index that syncs only after normalization is stale exactly when it is used.

### Inserts and splits

Structural changes are applied right away. A new block goes into its neighbour’s leaf. If the leaf now has more than *B* blocks, it splits in two and its parent gets one more child. If the parent overflows, it splits the same way, up to the root.

```ts
function insertAfter(prev: Unit, unit: Unit): void {
  const leaf = leafOf.get(prev)!;
  const at = leaf.units.indexOf(prev) + 1;
  leaf.units.splice(at, 0, unit);
  leaf.lengths.splice(at, 0, unit.length());
  leafOf.set(unit, leaf);
  addToPath(leaf, unit.length());          // the same walk up as update()
  if (leaf.units.length > B) split(leaf);  // may climb to the root
}
```

[Diagram: A full leaf of 32 receives one more block and becomes 33, over the limit. It splits into leaves of 16 and 17 blocks and the parent gains a child.]

**Figure 7.** A full leaf takes one more block and splits into 16 and 17. The parent gets one more child, and nothing else in the tree moves.

### Deletes and rebuilding

Textbook B-trees rebalance on delete by borrowing from a sibling or merging with it. I’d skip that. Empty nodes are removed, and underfull nodes simply stay underfull. A sparse node costs a few extra comparisons, while borrow-and-merge code is where index bugs usually live.

Sparse nodes still add up over time, so the tree is rebuilt from the editor’s list once the number of live blocks drops below half of $n_0$, the size at the last rebuild. A rebuild is linear, but at least $n_0/2$ deletes happened before it, so its cost per delete is constant:

$$
\frac{C_{\text{rebuild}}}{\#\text{deletions}} \le \frac{c\,n_0/2}{n_0/2} = O(1) \ \text{amortized per deletion}
$$

A rebuilt tree packs every node full and has the minimal height again.

```ts
function onDelete(): void {
  liveUnits--;
  if (liveUnits < sizeAtLastRebuild / 2) {
    rebuildFrom(scroll.children);  // O(n), paid for by n/2 deletes
    sizeAtLastRebuild = liveUnits;
  }
}
```

Errors are handled the same way. If measuring a block throws, or a structural update hits a state that should be impossible, the tree empties itself and refuses queries until the next rebuild. The mutation that caused it never sees the exception. A bug in the index turns into no index, never into a broken editor.

## Checking the index against the list

An index under an editor cannot be “mostly right”. Fortunately, the editor already has a perfect reference: the slow loop. It is simple, it has worked for years, and it answers the same questions. So we run both and compare.

The checks come in two levels. Cheap checks, like total length and block count, run after every change. A full check compares `select` and `rank` at the start and end of the document, at the caret and at random positions, plus every block id. It is expensive, so it runs on a random fraction $p$ of changes:

$$
\mathbb{E}\left[C_{\text{verify}}\right] = C_{\text{cheap}} + p \cdot C_{\text{full}}
$$

This turns $p$ into a budget instead of a guess. To keep verification under a fraction $\varepsilon$ of an average operation:

$$
p \le \frac{\varepsilon\, C_{\text{op}} - C_{\text{cheap}}}{C_{\text{full}}} \qquad \text{e.g.}\ \ \varepsilon = 5\%,\ \ C_{\text{full}} = 5\,C_{\text{op}},\ \ C_{\text{cheap}} \approx 0 \;\Rightarrow\; p \le 1\%
$$

```ts
const FULL_CHECK_RATE = 0.01;
const MAX_REBUILDS = 3;

function verify(): void {
  if (tree.sum.length !== scroll.length() || tree.sum.units !== scroll.children.length) {
    return recover('aggregate');
  }
  if (Math.random() < FULL_CHECK_RATE && !fullCheckPasses()) recover('full');
}

function recover(reason: string): void {
  report('index-divergence', { reason });  // never throw
  if (++rebuilds > MAX_REBUILDS) return retire();  // back to the loop for this session
  rebuildFrom(scroll.children);
}
```

A natural question is how long a bug can hide with only 1% of changes checked. If the tree goes wrong and stays wrong, each change has an independent chance $p$ to run the full check, so the bug survives $t$ changes with probability:

$$
P_{\text{miss}}(t) = (1 - p)^t \approx e^{-pt} \qquad p = 0.01:\ \ P_{\text{miss}}(100) \approx 0.37,\ \ P_{\text{miss}}(460) \approx 0.01
$$

A bug that breaks the total length is caught on the next change by the cheap check.

[Diagram: Probability that a persistent divergence is still undetected after t changes, for sampling rates of 1% and 0.1%. At 1%, it falls below 1% after about 460 changes.]

**Figure 8.** The chance that a persistent bug is still undetected after $t$ changes. With a 1% check rate, a few hundred keystrokes are enough to find it.

When a check fails, the index records it, rebuilds from the list and continues. The number of rebuilds per session is capped at $R$. A mismatch that survives several rebuilds is a real bug, and rebuilding on every keystroke would cost more than the loop it replaces. So the worst case is bounded by $O(R \cdot n)$, after which the index retires and all reads go back to the loop.

That fallback is part of the design. Every indexed read keeps the original loop as its else branch:

```ts
function lineAt(index: number): Line | null {
  const tree = usableIndex();            // null while batching, after a failure or after retiring
  const hit = tree?.select(index);
  if (hit) return lineInside(hit.unit, index - hit.start);
  return walkFromHead(index);            // the original loop, unchanged
}
```

An index that says “I don’t know” costs speed, never correctness.

### What not to index

Some reads should not go through the tree even when they could:

-   **Reads inside a batch.** If each read flushes the dirty set and a batch reads once per operation, every operation re-measures what the previous one changed. Let the batch use the loop, and flush once at the end.
-   **Iterating the whole document.** There is nothing to look up, so the tree only adds work.
-   **APIs with a different consistency model.** If an API answers from a snapshot taken after the last transaction while the tree reads live blocks, the two legitimately disagree in the middle of a transaction. Serving that API from the tree would quietly change its answers.

## Where this is going

The real reason for the tree is virtualization. A virtualized editor renders real blocks only around the viewport and replaces the rest with placeholders. With $n = 10{,}000$ blocks and a window of about a hundred, only 1% of the document is in the DOM and rendering costs $O(\text{window})$ instead of $O(n)$, but every positional query still has to be right about the other 99%.

For the tree, a placeholder is just another unit whose summary is the sum of the blocks it stands for:

$$
\operatorname{sum}(g) = \bigoplus_{u \,\in\, \operatorname{run}(g)} \operatorname{sum}(u)
$$

The id map can point to blocks that were never rendered, so a link to the last paragraph finds the placeholder that holds it, and the editor renders exactly that part. The height summary answers “what is at this y?” from estimates until real measurements replace them. Swapping real blocks for a placeholder has to happen in one batch, with no flush in between, or one query will count those blocks twice. This is the subject of part two.

## Conclusion

In conclusion, positional reads in a block editor are a dynamic partial-sums problem, and a linked-list walk answers them in linear time. A B+ tree that stores subtree sums instead of keys answers the same questions in a few comparisons, carries several aggregates at once, and stays a cache next to the editor’s own list. Lazy length updates keep typing cheap, rebuilding replaces delete rebalancing, and sampled checks against the original loop catch mistakes early. The loop itself doesn’t go away: it becomes the fallback, so the worst case is the editor working exactly as it did before.

[Previous: Can You Still Program Without AI?](https://fyvfyv.com/blog/can-you-still-program-without-ai)
