# Algorithm to Bulk Delete nodes from a Treap

I have a Treap, and want to bulk delete nodes in a given key range (i.e. the nodes to be deleted are consecutive nodes in an in-order walk of the tree). If I have $n$ nodes in the Treap, and $k$ nodes are to be deleted, is there an algorithm that can let me do this in $O(k + \log n)$. Or maybe provide a lower-bound proof that shows that that is impossible?

The obvious algorithm seems to be the one where the following steps are performed:

1. The treap is first split into 2 treaps by rotating the predecessor of the first node to be deleted to the root: $O(\log n)$
2. Detach the right child of the root: $O(1)$
3. Rotate the successor of the last node to be deleted in the detached treap and throw away the left subtree of this treap: $O(\log n)$
4. Meld the 2 remaining treaps: $O(\log n)$

However, I'm worried that the treap will get skewed (or will they)?

• It may be worth mentioning explicitly that it's very easy to do bulk deletes in $O(\log n)$ while maintaining the treap property. The issue is that the probabilistic performance bounds will no longer apply. Whether or not that's an issue in your algorithm depends on how you meld the treaps. – SamM Feb 23 '14 at 17:24
• @SamM Hello! :) So can we prove that the above algorithm doesn't maintain the expected height bounds? I can intuitively see that it doesn't. Is it possible to "fix" the algorithm by performing some rotations post the meld operation? – dhruvbird Feb 24 '14 at 3:14
• The operation you described (removing a set of consecutively-ranked keys) is called excision. And yes, you can do that in treaps. See Section 5.9 of the journal paper. – Maverick Woo Mar 21 '14 at 21:17

In order to split a treap storing $X$ according to some $a$, simply insert an item with key $a$ and "infinite" priority. By the heap-order property the newly inserted item will be at the root of the new treap. By the in-order property the left subtree of the root will be a treap for $X_1$ and the right subtree will be a treap for $X_2$. In order to join the treaps of two sets $X_1$ and $X_2$ as above, simply create a dummy root whose left subtree is a treap for $X_1$ and whose right subtree is a treap for $X_2$, and perform a delete operation on the dummy root.