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

Правка en1, от brunomont, 2026-11-30 04:59:58

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)$$$, I guessed that the algorithm would cut between adjacent elements only $$$\mathcal O(\log U)$$$ times per operation on average. That would give $$$\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 $$$\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 $$$n$$$ elements in total, with every sequence represented by a regular implicit treap. We want to support the following operations:

  1. Split by index: first $$$k$$$ 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 $$$ \lt x$$$ / elements $$$\ge x$$$, preserving order on each side.

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

Let the cost of a value split be the number $$$r$$$ of indices $$$i$$$ where $$$[a_i \lt x] \ne [a_{i+1} \lt x]$$$. It's not hard to implement a nontrivial split in expected $$$\mathcal O(r\log n)$$$ time.

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

The expected amortized running time per operation is therefore

$$$ \mathcal O(\sqrt n\log n). $$$

Implementation of split by value

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

Fix a threshold $$$x$$$. Label each element $$$L$$$ if its value is less than $$$x$$$ and $$$H$$$ otherwise. A transition is a change from $$$L$$$ to $$$H$$$ or from $$$H$$$ to $$$L$$$ at consecutive indices. For example, the word $$$LLLLHHLHHHHHLLL$$$ 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 $$$L$$$ output. If mn >= x, it goes to the $$$H$$$ 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 $$$L$$$ pieces into one output and the $$$H$$$ pieces into the other, preserving the original left-to-right order in each.

First count the recursive calls. Let $$$h$$$ 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 ($$$LH$$$ or $$$HL$$$). Each of the $$$r$$$ transitions lies in at most $$$h$$$ subtrees, and each expanded node makes $$$\mathcal O(1)$$$ recursive calls. Therefore there are $$$\mathcal O(rh)$$$ recursive calls.

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

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

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

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

Amortized analysis

Theorem. Suppose the collection contains $$$n$$$ elements in total and we perform $$$q\ge n$$$ operations. If value split $$$i$$$ has $$$r_i$$$ transitions, then $$$\sum_i r_i=\mathcal O(q\sqrt n)$$$.

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

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,2$$$, so the walk goes from $$$1$$$ to $$$6$$$ (a distance of $$$5$$$), then back to $$$2$$$ (a distance of $$$4$$$). Let $$$L$$$ be the total length of these walks over all sequences. A concatenation adds a single edge of length at most $$$n-1$$$, so dividing $$$L$$$ by $$$\sqrt n$$$ makes its potential increase at most $$$\sqrt n$$$. We use

$$$ \Phi=\frac{L}{\sqrt n}, \qquad L=\sum\limits_{(a,b)\,\text{adjacent}}|\rho(a)-\rho(b)|. $$$

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

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

$$$ A_y=\sum\limits_{(a,b)\,\text{adjacent}} \bigl[\min(\rho(a),\rho(b))\le y \lt \max(\rho(a),\rho(b))\bigr]. $$$

The bracket is $$$1$$$ when one endpoint lies on each side of the cut and $$$0$$$ otherwise. An edge of length $$$d$$$ crosses exactly $$$d$$$ cuts, so $$$L=\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 $$$5$$$ is crossed eight times, so $$$A_5=8$$$. Summing over all nine cuts gives the walk length $$$L=38$$$.

Splitting at $$$k$$$ puts the ranks at most $$$k$$$ in the $$$L$$$ output and the ranks above $$$k$$$ in the $$$H$$$ output. Now consider a further split at $$$y$$$. If $$$y \lt k$$$, it can only cut $$$L$$$. If $$$y \gt k$$$, it can only cut $$$H$$$. Take two consecutive elements $$$a,b$$$ in that output on opposite sides of $$$y$$$. In the original sequence, going from the index of $$$a$$$ to the index of $$$b$$$ must also cross $$$y$$$ at least once. Therefore, after the split at $$$k$$$, we have $$$A_y^{\rm after}\le A_y^{\rm before}$$$ for every cut $$$y$$$.

For each cut $$$y$$$, let $$$D_y=A_y^{\rm before}-A_y^{\rm after}\ge0$$$, where we count crossings at $$$y$$$ before and after the split at $$$k$$$. At the chosen cut $$$k$$$, all $$$r$$$ crossings disappear, so $$$D_k=r$$$.

In Figure 1, move the cut from just after rank $$$5$$$ to just after rank $$$6$$$. Only $$$6$$$ moves from the right side of the cut to the left. The input starts with $$$1,6,2$$$, so the steps $$$1\to6$$$ and $$$6\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 $$$k$$$ fixed and move the cut where we count crossings from $$$y$$$ to $$$y+1$$$. Only rank $$$y+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

$$$ |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 $$$|D_{y+1}-D_y|\le 4$$$.

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

$$$ \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 $$$y$$$, and the height $$$D_y$$$ tells us how many crossings the split at $$$k$$$ removed at that cut. Join consecutive points $$$(y,D_y)$$$ with straight lines. Between $$$y$$$ and $$$y+1$$$, the strip under the line has width $$$1$$$ and area $$$D_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 $$$D_0=D_n=0$$$, the total area is $$$\sum_y D_y=\Delta L$$$.

At the chosen cut $$$k$$$, the graph reaches height $$$r$$$. Moving away from $$$k$$$ in either direction, it takes at least $$$r/4$$$ units to fall to zero, because the height changes by at most $$$4$$$ per unit. The triangle drawn with slope $$$4$$$ on the left and $$$-4$$$ on the right therefore fits under the graph. Its height is $$$r$$$ and its base is $$$r/2$$$, so $$$\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 $$$L$$$, here $$$30$$$. The orange triangle gives the lower bound $$$r^2/4=16$$$.

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

$$$ \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 $$$\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 $$$\Delta\Phi\le 0$$$.
  2. Concatenate two sequences. Joining their endpoints adds at most one edge of length at most $$$n-1$$$, so $$$\Delta\Phi\le\sqrt n$$$.
  3. Reverse an entire sequence. Reversing the walk traverses the same edges backwards, so $$$\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-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 $$$L$$$ increases by at most $$$\mathcal O(n)$$$ and $$$\Delta\Phi$$$ is at most $$$\mathcal O(\sqrt n)$$$.

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

Can the full bound be logarithmic?

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

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

Split at $$$4$$$. All seven adjacencies cross the threshold, and the outputs $$$[0,2,1,3]$$$ and $$$[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 $$$d$$$, every adjacency in each of the $$$2^d$$$ sequences is a transition, for $$$n-2^d$$$ in total. Reaching singletons takes $$$n-1$$$ splits and costs

$$$ \sum_{d=0}^{k-1}(n-2^d)=n\log_2 n-n+1 $$$

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

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

$$$ \Omega(\log n)\ \le\ P_{\rm stable}(n)\ \le\ \mathcal O(\sqrt n), $$$

where $$$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.me/blog/entry/111450

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский brunomont 2026-11-30 04:59:58 12715 Initial revision (published)