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 , I guessed that the algorithm would cut between adjacent elements only times per operation on average. That would give expected amortized time, but I couldn’t prove the bound on the number of cuts. It turns out we can prove expected amortized time per operation. Here is a precise version of the problem.
Maintain a collection of sequences containing elements in total, with every sequence represented by a regular implicit treap. We want to support the following operations:
- Split by index: first elements / remaining suffix;
- Concatenate two sequences;
- Reverse an entire sequence;
- Set the value at a given index;
- Query the sum over an index range;
- Stable partition by value: elements / elements , preserving order on each side.
For example, and produces and .
Let the cost of a value split be the number of indices where . It’s not hard to implement a nontrivial split in expected time.
With the help of AI, I found a proof that over any sequence of operations, the total number of adjacent pairs separated by these value splits is .
The expected amortized running time per operation is therefore
Implementation of split by value
We can implement the split in expected time with a single recursive function.
Fix a threshold . Label each element if its value is less than and otherwise. A transition is a change from to or from to at consecutive indices. For example, the word 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 output. If mn >= x, it goes to the 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 pieces into one output and the pieces into the other, preserving the original left-to-right order in each.
First count the recursive calls. Let 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 ( or ). Each of the transitions lies in at most subtrees, and each expanded node makes recursive calls. Therefore there are recursive calls.
Now sum the cost of all the merges across those recursive calls. Suppose the current node has label , that is, t->val < x. Consider the two merge expressions in this branch.
merge(ll, merge(t, rl))takes constant time. Since has the highest priority in its subtree, the inner merge attachesrlas the right child of , and the outer merge attachesllas its left child.merge(lh, rh)has both arguments nonempty at most once per run of elements. Consider the run containing . If both arguments are nonempty, the last inlhis the element immediately before the run, and the first inrhis the element immediately after it. These two elements lie in different child subtrees of . Therefore, only their lowest common ancestor can callmerge(lh, rh)with both arguments nonempty in this run.
The same arguments apply when has label . In that branch, merge(lh, merge(t, rh)) takes constant time, and at most one node in each run of elements calls merge(ll, rl) with both arguments nonempty.
There are runs, so only merges can take more than constant time. Each of them costs time because it is a single treap merge. Together with the constant work per recursive call, this gives total time. Since , the split takes expected time.
Amortized analysis
Theorem. Suppose the collection contains elements in total and we perform operations. If value split has transitions, then .
Proof. For the analysis, we first compress the coordinates. Sort all elements in the collection by value, breaking ties by a fixed ID, and give them ranks in that order. Write for the rank of element . If elements have value , then splitting at is the same as cutting the rank line just after .
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 , so the walk goes from to (a distance of ), then back to (a distance of ). Let be the total length of these walks over all sequences. A concatenation adds a single edge of length at most , so dividing by makes its potential increase at most . We use
We count transitions for a value split and zero for every other operation. The amortized transition cost is , where .
A split with transitions shortens the walks by at least . To see why, draw a cut after each integer rank . The number of adjacent pairs crossing that cut is
The bracket is when one endpoint lies on each side of the cut and otherwise. An edge of length crosses exactly cuts, so .
Figure 1. The cut after rank is crossed eight times, so . Summing over all nine cuts gives the walk length .
Splitting at puts the ranks at most in the output and the ranks above in the output. Now consider a further split at . If , it can only cut . If , it can only cut . Take two consecutive elements in that output on opposite sides of . In the original sequence, going from the index of to the index of must also cross at least once. Therefore, after the split at , we have for every cut .
For each cut , let , where we count crossings at before and after the split at . At the chosen cut , all crossings disappear, so .
In Figure 1, move the cut from just after rank to just after rank . Only moves from the right side of the cut to the left. The input starts with , so the steps and 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 fixed and move the cut where we count crossings from to . Only rank 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
Therefore we get .
Let be the total walk length lost in the split. Since , we have
In Figure 2, the horizontal axis is the cut , and the height tells us how many crossings the split at removed at that cut. Join consecutive points with straight lines. Between and , the strip under the line has width and area . Each interior height contributes half to the strip on its left and half to the strip on its right. Since , the total area is .
At the chosen cut , the graph reaches height . Moving away from in either direction, it takes at least units to fall to zero, because the height changes by at most per unit. The triangle drawn with slope on the left and on the right therefore fits under the graph. Its height is and its base is , so .
Figure 2. The area under the blue curve is the actual drop in , here . The orange triangle gives the lower bound .
Since , the change in potential is . Now we can bound the amortized cost:
The square is nonnegative, so the amortized cost is at most .
For every other operation, the amortized transition cost is just .
- Split by index. Splitting removes the edge between the prefix and suffix if both are nonempty, so .
- Concatenate two sequences. Joining their endpoints adds at most one edge of length at most , so .
- Reverse an entire sequence. Reversing the walk traverses the same edges backwards, so .
- Set the value at a given index. At most two edges touch the updated element, and each can grow by at most . 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 increases by at most and is at most .
The amortized costs sum to . The total number of transitions is at most this sum plus the initial potential, and .
Can the full bound be logarithmic?
For a lower bound, take and list in bit-reversal order. For this is
Split at . All seven adjacencies cross the threshold, and the outputs and 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 , every adjacency in each of the sequences is a transition, for in total. Reaching singletons takes splits and costs
transitions. With another concatenations we can rebuild the original sequence from its singletons and repeat the cycle. This gives amortized transitions even over arbitrarily many operations.
So for operations, with splits by index, arbitrary concatenations, reversals of entire sequences, point assignments, and stable value splits, the gap is still
where 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