[Algorithm note] You can stably split implicit BSTs by value

2026-11-30 · Originally published on Codeforces

Hello, Codeforces!

A few years ago I asked here whether a stable partition by value on a treap could be better than linear amortized. For integer values in [0,U)[0,U), I guessed that the algorithm would cut between adjacent elements only O(log⁡U)\mathcal O(\log U) times per operation on average. That would give O(log⁡Ulog⁡n)\mathcal O(\log U\log n) expected amortized time, but I couldn’t prove the bound on the number of cuts. It turns out we can prove O(nlog⁡n)\mathcal O(\sqrt n\log n) expected amortized time per operation. Here is a precise version of the problem.

Maintain a collection of sequences containing nn elements in total, with every sequence represented by a regular implicit treap. We want to support the following operations:

  1. Split by index: first kk elements / remaining suffix;
  2. Concatenate two sequences;
  3. Reverse an entire sequence;
  4. Set the value at a given index;
  5. Query the sum over an index range;
  6. Stable partition by value: elements <x<x / elements ≥x\ge x, preserving order on each side.

For example, T=[7,1,9,3,8,2]T = [7, 1, 9, 3, 8, 2] and x=5x = 5 produces [1,3,2][1, 3, 2] and [7,9,8][7, 9, 8].

Let the cost of a value split be the number rr of indices ii where [ai<x]≠[ai+1<x][a_i < x] \ne [a_{i+1} < x]. It’s not hard to implement a nontrivial split in expected O(rlog⁡n)\mathcal O(r\log n) time.

With the help of AI, I found a proof that over any sequence of q≥nq\ge n operations, the total number of adjacent pairs separated by these value splits is O(qn)\mathcal O(q\sqrt n).

The expected amortized running time per operation is therefore

O(nlog⁡n).\mathcal O(\sqrt n\log n).

Implementation of split by value

We can implement the split in expected O(rlog⁡n)\mathcal O(r\log n) time with a single recursive function.

Fix a threshold xx. Label each element LL if its value is less than xx and HH otherwise. A transition is a change from LL to HH or from HH to LL at consecutive indices. For example, the word LLLLHHLHHHHHLLLLLLLHHLHHHHHLLL has five runs and four transitions.

Each node stores the minimum mn and maximum mx of its subtree alongside the usual size, sum, and lazy reversal tag. If mx < x, the whole subtree goes to the LL output. If mn >= x, it goes to the HH output. Otherwise we split both children recursively.

std::pair<Node*, Node*> split_value(Node* t, long long x) {
	if (!t) return {nullptr, nullptr};
	push(t);

	if (t->mx < x)
		return {t, nullptr};
	if (t->mn >= x)
		return {nullptr, t};

	auto [ll, lh] = split_value(t->l, x);
	auto [rl, rh] = split_value(t->r, x);

	t->l = t->r = nullptr;
	pull(t);

	if (t->val < x)
		return {merge(ll, merge(t, rl)), merge(lh, rh)};
	else
		return {merge(ll, rl), merge(lh, merge(t, rh))};
}

Algorithm 1: stable split by value.

The merges concatenate the LL pieces into one output and the HH pieces into the other, preserving the original left-to-right order in each.

First count the recursive calls. Let hh be the maximum height among all treaps involved in this split. We expand a node only if its subtree contains a transition between two consecutive elements (LHLH or HLHL). Each of the rr transitions lies in at most hh subtrees, and each expanded node makes O(1)\mathcal O(1) recursive calls. Therefore there are O(rh)\mathcal O(rh) recursive calls.

Now sum the cost of all the merges across those recursive calls. Suppose the current node tt has label LL, that is, t->val < x. Consider the two merge expressions in this branch.

  1. merge(ll, merge(t, rl)) takes constant time. Since tt has the highest priority in its subtree, the inner merge attaches rl as the right child of tt, and the outer merge attaches ll as its left child.
  2. merge(lh, rh) has both arguments nonempty at most once per run of LL elements. Consider the run containing tt. If both arguments are nonempty, the last HH in lh is the element immediately before the run, and the first HH in rh is the element immediately after it. These two elements lie in different child subtrees of tt. Therefore, only their lowest common ancestor can call merge(lh, rh) with both arguments nonempty in this run.

The same arguments apply when tt has label HH. In that branch, merge(lh, merge(t, rh)) takes constant time, and at most one node in each run of HH elements calls merge(ll, rl) with both arguments nonempty.

There are r+1r+1 runs, so only O(r)\mathcal O(r) merges can take more than constant time. Each of them costs O(h)\mathcal O(h) time because it is a single treap merge. Together with the constant work per recursive call, this gives O(rh)\mathcal O(rh) total time. Since E[h]=O(log⁡n)\mathbb E[h]=\mathcal O(\log n), the split takes O(rlog⁡n)\mathcal O(r\log n) expected time.

Amortized analysis

Theorem. Suppose the collection contains nn elements in total and we perform q≥nq\ge n operations. If value split ii has rir_i transitions, then ∑iri=O(qn)\sum_i r_i=\mathcal O(q\sqrt n).

Proof. For the analysis, we first compress the coordinates. Sort all nn elements in the collection by value, breaking ties by a fixed ID, and give them ranks 1,…,n1,\ldots,n in that order. Write ρ(a)\rho(a) for the rank of element aa. If kk elements have value <x<x, then splitting at xx is the same as cutting the rank line just after kk.

Place the ranks on a number line and trace each sequence in index order, drawing an edge between every pair of consecutive elements. For example, the sequence in Figure 1 starts with ranks 1,6,21,6,2, so the walk goes from 11 to 66 (a distance of 55), then back to 22 (a distance of 44). Let LL be the total length of these walks over all sequences. A concatenation adds a single edge of length at most n−1n-1, so dividing LL by n\sqrt n makes its potential increase at most n\sqrt n. We use

Φ=Ln,L=∑(a,b) adjacent∣ρ(a)−ρ(b)∣.\Phi=\frac{L}{\sqrt n}, \qquad L=\sum\limits_{(a,b)\,\text{adjacent}}|\rho(a)-\rho(b)|.

We count rr transitions for a value split and zero for every other operation. The amortized transition cost is r+ΔΦr+\Delta\Phi, where ΔΦ=Φafter−Φbefore\Delta\Phi=\Phi^{\rm after}-\Phi^{\rm before}.

A split with rr transitions shortens the walks by at least r2/4r^2/4. To see why, draw a cut after each integer rank yy. The number of adjacent pairs crossing that cut is

Ay=∑(a,b) adjacent[min⁡(ρ(a),ρ(b))≤y<max⁡(ρ(a),ρ(b))].A_y=\sum\limits_{(a,b)\,\text{adjacent}} \bigl[\min(\rho(a),\rho(b))\le y<\max(\rho(a),\rho(b))\bigr].

The bracket is 11 when one endpoint lies on each side of the cut and 00 otherwise. An edge of length dd crosses exactly dd cuts, so L=∑yAyL=\sum_y A_y.

The nine moves on the rank line, with an orange dot wherever a move crosses the cut after rank 5.

Figure 1. The cut after rank 55 is crossed eight times, so A5=8A_5=8. Summing over all nine cuts gives the walk length L=38L=38.

Splitting at kk puts the ranks at most kk in the LL output and the ranks above kk in the HH output. Now consider a further split at yy. If y<ky<k, it can only cut LL. If y>ky>k, it can only cut HH. Take two consecutive elements a,ba,b in that output on opposite sides of yy. In the original sequence, going from the index of aa to the index of bb must also cross yy at least once. Therefore, after the split at kk, we have Ayafter≤AybeforeA_y^{\rm after}\le A_y^{\rm before} for every cut yy.

For each cut yy, let Dy=Aybefore−Ayafter≥0D_y=A_y^{\rm before}-A_y^{\rm after}\ge0, where we count crossings at yy before and after the split at kk. At the chosen cut kk, all rr crossings disappear, so Dk=rD_k=r.

In Figure 1, move the cut from just after rank 55 to just after rank 66. Only 66 moves from the right side of the cut to the left. The input starts with 1,6,21,6,2, so the steps 1→61\to6 and 6→26\to2 used to cross the cut, and now both lie entirely to its left. Every other step keeps both endpoints on their original sides.

Keep the split at kk fixed and move the cut where we count crossings from yy to y+1y+1. Only rank y+1y+1 switches sides. At most two steps touch that rank in the input walk, one arriving and one leaving. The same holds after the split. Thus

∣Ay+1before−Aybefore∣≤2and∣Ay+1after−Ayafter∣≤2.|A_{y+1}^{\rm before}-A_y^{\rm before}|\le 2 \qquad\text{and}\qquad |A_{y+1}^{\rm after}-A_y^{\rm after}|\le 2.

Therefore we get ∣Dy+1−Dy∣≤4|D_{y+1}-D_y|\le 4.

Let ΔL\Delta L be the total walk length lost in the split. Since L=∑yAyL=\sum_y A_y, we have

ΔL=Lbefore−Lafter=∑y(Aybefore−Ayafter)=∑yDy.\Delta L=L^{\rm before}-L^{\rm after} =\sum_y \bigl(A_y^{\rm before}-A_y^{\rm after}\bigr) =\sum_y D_y.

In Figure 2, the horizontal axis is the cut yy, and the height DyD_y tells us how many crossings the split at kk removed at that cut. Join consecutive points (y,Dy)(y,D_y) with straight lines. Between yy and y+1y+1, the strip under the line has width 11 and area Dy/2+Dy+1/2D_y/2+D_{y+1}/2. Each interior height contributes half to the strip on its left and half to the strip on its right. Since D0=Dn=0D_0=D_n=0, the total area is ∑yDy=ΔL\sum_y D_y=\Delta L.

At the chosen cut kk, the graph reaches height rr. Moving away from kk in either direction, it takes at least r/4r/4 units to fall to zero, because the height changes by at most 44 per unit. The triangle drawn with slope 44 on the left and −4-4 on the right therefore fits under the graph. Its height is rr and its base is r/2r/2, so ΔL≥r2/4\Delta L\ge r^2/4.

Drop in crossings for a split after rank 5. The graph peaks at 8 and has area 30. The inscribed triangle has base 4, height 8, and area 16.

Figure 2. The area under the blue curve is the actual drop in LL, here 3030. The orange triangle gives the lower bound r2/4=16r^2/4=16.

Since Φ=L/n\Phi=L/\sqrt n, the change in potential is ΔΦ=−ΔL/n≤−r2/(4n)\Delta\Phi=-\Delta L/\sqrt n\le -r^2/(4\sqrt n). Now we can bound the amortized cost:

r+ΔΦ≤r−r24n=4rn−r24n=4n−(r2−4rn+4n)4n=n−(r−2n)24n≤n.\begin{aligned} r+\Delta\Phi &\le r-\frac{r^2}{4\sqrt n}\\ &=\frac{4r\sqrt n-r^2}{4\sqrt n}\\ &=\frac{4n-(r^2-4r\sqrt n+4n)}{4\sqrt n}\\ &=\sqrt n-\frac{(r-2\sqrt n)^2}{4\sqrt n}\\ &\le \sqrt n. \end{aligned}

The square is nonnegative, so the amortized cost is at most n\sqrt n.

For every other operation, the amortized transition cost is just ΔΦ\Delta\Phi.

  1. Split by index. Splitting removes the edge between the prefix and suffix if both are nonempty, so ΔΦ≤0\Delta\Phi\le 0.
  2. Concatenate two sequences. Joining their endpoints adds at most one edge of length at most n−1n-1, so ΔΦ≤n\Delta\Phi\le\sqrt n.
  3. Reverse an entire sequence. Reversing the walk traverses the same edges backwards, so ΔΦ=0\Delta\Phi=0.
  4. Set the value at a given index. At most two edges touch the updated element, and each can grow by at most n−1n-1. Every other edge changes length by at most one, because only the updated element can enter or leave the gap between its endpoints in sorted order. Thus LL increases by at most O(n)\mathcal O(n) and ΔΦ\Delta\Phi is at most O(n)\mathcal O(\sqrt n).

The amortized costs sum to O(qn)\mathcal O(q\sqrt n). The total number of transitions is at most this sum plus the initial potential, and Φinitial≤nn≤qn\Phi_{\rm initial}\le n\sqrt n\le q\sqrt n. □\square

Can the full bound be logarithmic?

For a lower bound, take n=2kn=2^k and list 0,…,n−10,\ldots,n-1 in bit-reversal order. For n=8n=8 this is

[0,4,2,6,1,5,3,7].[0,4,2,6,1,5,3,7].

Split at 44. All seven adjacencies cross the threshold, and the outputs [0,2,1,3][0,2,1,3] and [4,6,5,7][4,6,5,7] alternate at their own median cuts. In general the leading bit alternates, and filtering on it gives the same construction on one fewer bit (with an offset in the upper half). At depth dd, every adjacency in each of the 2d2^d sequences is a transition, for n−2dn-2^d in total. Reaching singletons takes n−1n-1 splits and costs

∑d=0k−1(n−2d)=nlog⁡2n−n+1\sum_{d=0}^{k-1}(n-2^d)=n\log_2 n-n+1

transitions. With another n−1n-1 concatenations we can rebuild the original sequence from its singletons and repeat the cycle. This gives Ω(log⁡n)\Omega(\log n) amortized transitions even over arbitrarily many operations.

So for Θ(n)\Theta(n) operations, with splits by index, arbitrary concatenations, reversals of entire sequences, point assignments, and stable value splits, the gap is still

Ω(log⁡n) ≤ Pstable(n) ≤ O(n),\Omega(\log n)\ \le\ P_{\rm stable}(n)\ \le\ \mathcal O(\sqrt n),

where Pstable(n)P_{\rm stable}(n) is the worst-case amortized transition count. Can we prove the logarithmic upper bound for arbitrary concatenations, or find a repeatable construction that beats it?

References

Can you find the time complexity?: https://codeforces.com/blog/entry/111450