Docsity

Lecture 10: Treaps and Skip Lists - Randomized Binary Search Trees and Skip Lists, Study notes of Algorithms and Programming

Toggle sidebar
bg1
Algorithms Lecture 10: Treaps and Skip Lists
I thought the following four [rules] would be enough, provided that I made a firm and
constant resolution not to fail even once in the observance of them. The first was
never to accept anything as true if I had not evident knowledge of its being so. .. . The
second, to divide each problem I examined into as many parts as was feasible, and
as was requisite for its better solution. The third, to direct my thoughts in an orderly
way. .. establishing an order in thought even when the objects had no natural priority
one to another. And the last, to make throughout such complete enumerations and such
general surveys that I might be sure of leaving nothing out.
— René Descartes, Discours de la Méthode (1637)
What is luck?
Luck is probability taken personally.
It is the excitement of bad math.
— Penn Jillette (2001)
10 Randomized Binary Search Trees
In this lecture, we consider two randomized alternatives to balanced binary search tree structures such
as AVL trees, red-black trees, B-trees, or splay trees, which are arguably simpler than any of these
deterministic structures.
10.1 Treaps
Atreap is a binary tree in which every node has both a search key and a priority, where the inorder
sequence of search keys is sorted and each node’s priority is smaller than the priorities of its children.
1
In other words, a treap is simultaneously a binary search tree for the search keys and a (min-)heap for
the priorities. In our examples, we will use letters for the search keys and numbers for the priorities.
5
A L
G
O
RI
TH
M
1
2 3
7
98
4
6
A treap. The top half of each node shows its search key and the bottom half shows its priority.
I’ll assume from now on that all the keys and priorities are distinct. Under this assumption, we can
easily prove by induction that the structure of a treap is completely determined by the search keys and
priorities of its nodes. Since it’s a heap, the node
v
with highest priority must be the root. Since it’s also
a binary search tree, any node
u
with
key
(
u
)
<key
(
v
)must be in the left subtree, and any node
w
with
key
(
w
)
>key
(
v
)must be in the right subtree. Finally, since the subtrees are treaps, by induction, their
structures are completely determined. The base case is the trivial empty treap.
Another way to describe the structure is that a treap is exactly the binary tree that results by inserting
the nodes one at a time into an initially empty tree, in order of increasing priority, using the usual
insertion algorithm. This is also easy to prove by induction.
1
Sometimes I hate English. Normally, ‘higher priority’ means ‘more important’, but ‘first priority’ is also more important
than ‘second priority’. Maybe ‘posteriority’ would be better; one student suggested ‘unimportance’.
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Lecture 10: Treaps and Skip Lists - Randomized Binary Search Trees and Skip Lists and more Study notes Algorithms and Programming in PDF only on Docsity!

I thought the following four [rules] would be enough, provided that I made a firm and constant resolution not to fail even once in the observance of them. The first was never to accept anything as true if I had not evident knowledge of its being so.... The second, to divide each problem I examined into as many parts as was feasible, and as was requisite for its better solution. The third, to direct my thoughts in an orderly way... establishing an order in thought even when the objects had no natural priority one to another. And the last, to make throughout such complete enumerations and such general surveys that I might be sure of leaving nothing out. — René Descartes, Discours de la Méthode (1637)

What is luck? Luck is probability taken personally. It is the excitement of bad math. — Penn Jillette (2001)

10 Randomized Binary Search Trees

In this lecture, we consider two randomized alternatives to balanced binary search tree structures such as AVL trees, red-black trees, B-trees, or splay trees, which are arguably simpler than any of these deterministic structures.

10.1 Treaps

A treap is a binary tree in which every node has both a search key and a priority , where the inorder sequence of search keys is sorted and each node’s priority is smaller than the priorities of its children.^1 In other words, a treap is simultaneously a binary search tree for the search keys and a (min-)heap for the priorities. In our examples, we will use letters for the search keys and numbers for the priorities.

5 A L

G

O

I R

H T

M 1

2 3

7

9 8

4

6 A treap. The top half of each node shows its search key and the bottom half shows its priority.

I’ll assume from now on that all the keys and priorities are distinct. Under this assumption, we can easily prove by induction that the structure of a treap is completely determined by the search keys and priorities of its nodes. Since it’s a heap, the node v with highest priority must be the root. Since it’s also a binary search tree, any node u with key ( u ) < key ( v ) must be in the left subtree, and any node w with key ( w ) > key ( v ) must be in the right subtree. Finally, since the subtrees are treaps, by induction, their structures are completely determined. The base case is the trivial empty treap. Another way to describe the structure is that a treap is exactly the binary tree that results by inserting the nodes one at a time into an initially empty tree, in order of increasing priority, using the usual insertion algorithm. This is also easy to prove by induction.

(^1) Sometimes I hate English. Normally, ‘higher priority’ means ‘more important’, but ‘first priority’ is also more important than ‘second priority’. Maybe ‘posteriority’ would be better; one student suggested ‘unimportance’.

A third description interprets the keys and priorities as the coordinates of a set of points in the plane. The root corresponds to a T whose joint lies on the topmost point. The T splits the plane into three parts. The top part is (by definition) empty; the left and right parts are split recursively. This interpretation has some interesting applications in computational geometry, which (unfortunately) we probably won’t have time to talk about.

A G H I L M O R T

1 2 3 4 5 6 7 8 9

A geometric interpretation of the same treap.

Treaps were first discovered by Jean Vuillemin in 1980, but he called them Cartesian trees.^2 The word ‘treap’ was first used by Edward McCreight around 1980 to describe a slightly different data structure, but he later switched to the more prosaic name priority search trees.^3 Treaps were rediscovered and used to build randomized search trees by Cecilia Aragon and Raimund Seidel in 1989.^4 A different kind of randomized binary search tree, which uses random rebalancing instead of random priorities, was later discovered and analyzed by Conrado Martínez and Salvador Roura in 1996.^5

10.2 Treap Operations

The search algorithm is the usual one for binary search trees. The time for a successful search is proportional to the depth of the node. The time for an unsuccessful search is proportional to the depth of either its successor or its predecessor. To insert a new node z , we start by using the standard binary search tree insertion algorithm to insert it at the bottom of the tree. At the point, the search keys still form a search tree, but the priorities may no longer form a heap. To fix the heap property, as long as z has smaller priority than its parent, perform a rotation at z , a local operation that decreases the depth of z by one and increases its parent’s depth by one, while maintaining the search tree property. Rotations can be performed in constant time, since they only involve simple pointer manipulation.

left

right x x y

y

A right rotation at x and a left rotation at y are inverses. (^2) J. Vuillemin, A unifying look at data structures. Commun. ACM 23:229–239, 1980. (^3) E. M. McCreight. Priority search trees. SIAM J. Comput. 14(2):257–276, 1985. (^4) R. Seidel and C. R. Aragon. Randomized search trees. Algorithmica 16:464–497, 1996. (^5) C. Martínez and S. Roura. Randomized binary search trees. J. ACM 45(2):288-323, 1998. The results in this paper are virtually identical (including the constant factors!) to the corresponding results for treaps, although the analysis techniques are quite different.

random real number between (say) 0 and 1 and use that number as the priority of the new node. The only reason we’re using real numbers is so that the probability of two nodes having the same priority is zero, since equal priorities make the analysis slightly messier. In practice, we could just choose random integers from a large range, like 0 to 2^31 − 1, or random floating point numbers. Also, since the priorities are independent, each node is equally likely to have the smallest priority. The cost of all the operations we discussed—search, insert, delete, split, join—is proportional to the depth of some node in the tree. Here we’ll see that the expected depth of any node is O (log n ), which implies that the expected running time for any of those operations is also O (log n ). Let xk denote the node with the k th smallest search key. To analyze the expected depth, we define an indicator variable Aik =

xi is a proper ancestor of xk

(The superscript doesn’t mean power in this case; it just a reminder of which node is supposed to be further up in the tree.) Since the depth of v is just the number of proper ancestors of v , we have the following identity: depth ( xk ) =

∑^ n

i = 1

Aik.

Now we can express the expected depth of a node in terms of these indicator variables as follows.

E[ depth ( xk )] =

∑^ n

i = 1

Pr[ Aik = 1 ]

(Just as in our analysis of matching nuts and bolts, we’re using linearity of expectation and the fact that E[ X ] = Pr[ X = 1 ] for any indicator variable X .) So to compute the expected depth of a node, we just have to compute the probability that some node is a proper ancestor of some other node. Fortunately, we can do this easily once we prove a simple structural lemma. Let X ( i , k ) denote either the subset of treap nodes { xi , xi + 1 ,... , xk } or the subset { xk , xk + 1 ,... , xi }, depending on whether i < k or i > k. X ( i , k ) and X ( k , i ) always denote prceisly the same subset, and this subset contains | k − i | + 1 nodes. X (1, n ) = X ( n , 1) contains all n nodes in the treap.

Lemma 1. For all i 6 = k , xi is a proper ancestor of xk if and only if xi has the smallest priority among all nodes in X ( i , k ).

Proof: If xi is the root, then it is an ancestor of xk , and by definition, it has the smallest priority of any node in the treap, so it must have the smallest priority in X ( i , k ). On the other hand, if xk is the root, then xi is not an ancestor of xk , and indeed xi does not have the smallest priority in X ( i , k ) — xk does. On the gripping hand^6 , suppose some other node x (^) j is the root. If xi and xk are in different subtrees, then either i < j < k or i > j > k , so x (^) j ∈ X ( i , k ). In this case, xi is not an ancestor of xk , and indeed xi does not have the smallest priority in X ( i , k ) — x (^) j does. Finally, if xi and xk are in the same subtree, the lemma follows inductively (or, if you prefer, recursively), since the subtree is a smaller treap. The empty treap is the trivial base case. É

Since each node in X ( i , k ) is equally likely to have smallest priority, we immediately have the (^6) See Larry Niven and Jerry Pournelle, The Gripping Hand, Pocket Books, 1994.

probability we wanted:

Pr[ Aik = 1 ] =

[ i 6 = k ] | k − i | + 1

k − i + 1

if i < k 0 if i = k 1 i − k + 1

if i > k

To compute the expected depth of a node xk , we just plug this probability into our formula and grind through the algebra.

E[ depth ( xk )] =

∑^ n

i = 1

Pr[ Aik = 1 ] =

k ∑− 1

i = 1

k − i + 1

∑^ n

i = k + 1

i − k + 1

∑^ k

j = 2

j

n −∑ k + 1

i = 2

j = Hk − 1 + Hn − k + 1 − 1 < ln k + ln( n − k + 1 ) − 2 < 2 ln n − 2.

In conclusion, every search, insertion, deletion, split, and merge operation in an n -node randomized binary search tree takes O (log n ) expected time. Since a treap is exactly the binary tree that results when you insert the keys in order of increasing priority, a randomized treap is the result of inserting the keys in random order. So our analysis also automatically gives us the expected depth of any node in a binary tree built by random insertions (without using priorities).

10.4 Randomized Quicksort (Again!)

We’ve already seen two completely different ways of describing randomized quicksort. The first is the familiar recursive one: choose a random pivot, partition, and recurse. The second is a less familiar iterative version: repeatedly choose a new random pivot, partition whatever subset contains it, and continue. But there’s a third way to describe randomized quicksort, this time in terms of binary search trees. RANDOMIZEDQUICKSORT: T ← an empty binary search tree insert the keys into T in random order output the inorder sequence of keys in T

Our treap analysis tells us is that this algorithm will run in O ( n log n ) expected time, since each key is inserted in O (log n ) expected time. Why is this quicksort? Just like last time, all we’ve done is rearrange the order of the comparisons. Intuitively, the binary tree is just the recursion tree created by the normal version of quicksort. In the recursive formulation, we compare the initial pivot against everything else and then recurse. In the binary tree formulation, the first “pivot” becomes the root of the tree without any comparisons, but then later as each other key is inserted into the tree, it is compared against the root. Either way, the first pivot chosen is compared with everything else. The partition splits the remaining items into a left subarray and a right subarray; in the binary tree version, these are exactly the items that go into the left

search key ( key ( v )), a pointer to its next lower copy ( down ( v )), and a pointer to the next node in its level ( right ( v )).

−∞ +∞

−∞ +∞

−∞ +∞

−∞ +∞

−∞ +∞

−∞ +∞

0 1 2 3 4 5 6 7 8 9

0 1 6 7 9

1 6 7

3

1 7

7

A skip list is a linked list with recursive random shortcuts.

The search algorithm for skip lists is very simple. Starting at the leftmost node L in the highest level, we scan through each level as far as we can without passing the target value x , and then proceed down to the next level. The search ends when we either reach a node with search key x or fail to find x on the lowest level.

SKIPLISTFIND( x , L ): v ← L while ( v 6 = NULL and key ( v ) 6 = x ) if key ( right ( v )) > x v ← down ( v ) else v ← right ( v ) return v

−∞ 0 1 2 3 4 5 6 7 8 9 +∞

−∞ 0 1 6 7 9 +∞

−∞ 1 6 7 +∞

3

−∞ 1 7 +∞

−∞ 7 +∞

−∞ +∞

Searching for 5 in a skip list.

Intuitively, since each level of the skip lists has about half the number of nodes as the previous level, the total number of levels should be about O (log n ). Similarly, each time we add another level of random shortcuts to the skip list, we cut the search time roughly in half, except for a constant overhead, so after O (log n ) levels, we should have a search time of O (log n ). Let’s formalize each of these two intuitive observations.

10.7 Number of Levels

The actual values of the search keys don’t affect the skip list analysis, so let’s assume the keys are the integers 1 through n. Let L ( x ) be the number of levels of the skip list that contain some search key x , not

counting the bottom level. Each new copy of x is created with probability 1 / 2 from the previous level, essentially by flipping a coin. We can compute the expected value of L ( x ) recursively—with probability 1 / 2, we flip tails and L ( x ) = 0; and with probability 1 / 2, we flip heads, increase L ( x ) by one, and recurse: E [ L ( x )] =

1 + E [ L ( x )]

Solving this equation gives us E [ L ( x )] = 1. In order to analyze the expected worst-case cost of a search, however, we need a bound on the number of levels L = max x L ( x ). Unfortunately, we can’t compute the average of a maximum the way we would compute the average of a sum. Instead, we will derive a stronger result, showing that the depth is O (log n ) with high probability. ‘High probability’ is a technical term that means the probability is at least 1 − 1 /nc^ for some constant c ≥ 1; the hidden constant in the O (log n ) bound could depend on c. In order for a search key x to appear on level _ , it must have flipped _ heads in a row when it was inserted, so Pr[ L ( x ) ≥ _** **] = 2 −** **_. The skip list has at least _ levels if and only if _L_ ( _x_ ) ≥ _ for at least one of the n search keys. Pr[ L ≥ ` ] = Pr

( L ( 1 ) ≥ _ ) ∨ ( _L_ ( 2 ) ≥ _ ) ∨ · · · ∨ ( L ( n ) ≥ ` )

Using the union bound — Pr[ A ∨ B ] ≤ P r [ A ] + Pr[ B ] for any random events A and B — we can simplify this as follows: Pr[ L ≥ ` ] ≤

∑^ n

x = 1

Pr[ L ( x ) ≥ _ ] = _n_ · Pr[ _L_ ( _x_ ) ≥ _ ] =

n 2 `^

When ` ≤ lg n , this bound is trivial. However, for any constant c > 1, we have a strong upper bound

Pr[ L ≥ c lg n ] ≤

nc −^1

We conclude that with high probability, a skip list has O (log n ) levels. This high-probability bound indirectly implies a bound on the expected number of levels. Some simple algebra gives us the following alternate definition for expectation:

E[ L ] =

` ≥ 0

_ · Pr[ _L_ = _ ] =

` ≥ 1

Pr[ L ≥ ` ]

Clearly, if < ′, then Pr[ L ( x ) ≥ _ ] _>_ Pr[ _L_ ( _x_ ) ≥ _ ′]. So we can derive an upper bound on the expected number of levels as follows: E[ L ( x )] =

` ≥ 1

Pr[ L ≥ ` ]

∑^ lg^ n

` = 1

Pr[ L ≥ ` ] +

` ≥lg n + 1

Pr[ L ≥ ` ]

∑^ lg^ n

` = 1

` ≥lg n + 1

n 2 `

= lg n +

i ≥ 1

2 i^

[ i = ` − lg n ]

= lg n + 2

So in expectation, a skip list has at most two more levels than an ideal version where each level contains exactly half the nodes of the next level below.

Exercises

  1. Prove that the expected number of proper descendants of any node in a treap is exactly equal to the expected depth of that node.
  2. What is the expected number of leaves in an n -node treap? [Hint: What is the probability that in an n -node treap, the node with k th smallest search key is a leaf?]
  3. Let x and y be two elements of a set S whose ranks differ by exactly r. Prove that in a treap for S , the expected length of the unique path from x to y is O (log r ). ? 4. In the usual theoretical presentation of treaps, the priorities are random real numbers chosen uniformly from the interval [ 0 , 1 ], but in practice, computers only have access to random bits. This problem asks you to analyze a modification of treaps that takes this limitation into account. Suppose the priority of a node v is abstractly represented as an infinite sequence πv [ 1 .. ∞] of random bits, which is interpreted as the rational number

priority ( v ) =

∑^ ∞

i = 1

πv [ i ] · 2 − i^.

However, only a finite number v_ of these bits are actually known at any given time. When a node _v_ is first created, _none_ of the priority bits are known: _v = 0. We generate (or ‘reveal’) new random bits only when they are necessary to compare priorities. The following algorithm compares the priorities of any two nodes in O ( 1 ) expected time:

LARGERPRIORITY( v , w ): for i ← 1 to ∞ if i > vv ← i ; πv [ i ] ← RANDOMBIT if i > ww ← i ; πw [ i ] ← RANDOMBIT if πv [ i ] > πw [ i ] return v else if πv [ i ] < πw [ i ] return w

Suppose we insert n items one at a time into an initially empty treap. Let L =

v `v^ denote the total number of random bits generated by calls to LARGERPRIORITY during these insertions.

(a) Prove that E [ L ] = Θ( n ). (b) Prove that E [ v_ ] = Θ( 1 ) for any node _v_. [Hint: This is equivalent to part (a). Why?] (c) Prove that _E_ [ _ root] = Θ(log n ). [Hint: Why doesn’t this contradict part (b)?]

  1. A meldable priority queue stores a set of keys from some totally-ordered universe (such as the integers) and supports the following operations: - MAKEQUEUE: Return a new priority queue containing the empty set. - FINDMIN( Q ): Return the smallest element of Q (if any).
  • DELETEMIN( Q ): Remove the smallest element in Q (if any).
  • INSERT( Q , x ): Insert element x into Q , if it is not already there.
  • DECREASEKEY( Q , x , y ): Replace an element x ∈ Q with a smaller key y. (If y > x , the operation fails.) The input is a pointer directly to the node in Q containing x.
  • DELETE( Q , x ): Delete the element x ∈ Q. The input is a pointer directly to the node in Q containing x.
  • MELD( Q 1 , Q 2 ): Return a new priority queue containing all the elements of Q 1 and Q 2 ; this operation destroys Q 1 and Q 2. A simple way to implement such a data structure is to use a heap-ordered binary tree, where each node stores a key, along with pointers to its parent and two children. MELD can be imple- mented using the following randomized algorithm: MELD( Q 1 , Q 2 ): if Q 1 is empty return Q 2 if Q 2 is empty return Q 1 if key ( Q 1 ) > key ( Q 2 ) swap Q 1 ↔ Q 2 with probability 1 / 2 left ( Q 1 ) ← MELD( left ( Q 1 ), Q 2 ) else right ( Q 1 ) ← MELD( right ( Q 1 ), Q 2 ) return Q 1

(a) Prove that for any heap-ordered binary trees Q 1 and Q 2 (not just those constructed by the operations listed above), the expected running time of MELD( Q 1 , Q 2 ) is O (log n ), where n = | Q 1 | + | Q 2 |. [Hint: How long is a random root-to-leaf path in an n -node binary tree if each left/right choice is made with equal probability?] (b) Prove that MELD( Q 1 , Q 2 ) runs in O (log n ) time with high probability. (c) Show that each of the other meldable priority queue operations can be implemented with at most one call to MELD and O ( 1 ) additional time. (This implies that every operation takes O (log n ) time with high probability.)

6. Any skip list L can be transformed into a binary search tree T (L) as follows. The root of T (L)

is the leftmost node on the highest non-empty level of L; the left and subtrees are constructed

recursively from the nodes to the left and to the right of the root. Let’s call the resulting tree T (L)

a skip list tree.

(a) Show that any search in T (L) is no more expensive than the corresponding search in L.

(Searching in T (L) could be considerably cheaper—why?)

(b) Describe an algorithm to insert a new search key into a skip list tree in O (log n ) expected

time. Inserting key x into T (L) should produce exactly the same tree as inserting x into L

and then transforming L into a tree. [Hint: You will need to maintain some additional

information in the tree nodes.] (c) Describe an algorithm to delete a search key from a skip list tree in O (log n ) expected time.

Again, deleting key x from T (L) should produce exactly the same tree as deleting x from L

and then transforming L into a tree.

© c Copyright 2008 Jeff Erickson. Released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License (http://creativecommons.org/licenses/by-nc-sa/3.0/). Free distribution is strongly encouraged; commercial distribution is expressly forbidden. See http://www.cs.uiuc.edu/~jeffe/teaching/algorithms/ for the most recent revision.