Skip Lists
Randomized express lanes: expected O(log n) search in a linked list.
A sorted linked list needs about hops to find a key. Give each node a random number of extra forward pointers, chosen by flipping coins, and a search drops to about moves: 32 for 65,536 keys in our simulation. Skip lists (Pugh, 1990) match balanced search trees in expectation without a single rotation, and that simplicity is why Java's ConcurrentSkipListMap, Redis's sorted sets and the in-memory tables of LevelDB and RocksDB are built on them.
What you’ll learn
- Define a skip list, and implement search and insertion with levels chosen by coin flips.
- Prove the expected search bound , with , by backward analysis, and the expected space.
- Show that the height and the search cost are with high probability, and choose .
- Compare skip lists with balanced trees and deterministic skip lists, and explain why concurrent ordered maps use them.
Express lanes over a sorted list
To search for a key, start at the header on the top level. Move right while the next key on this level is smaller than the target; when it is not, drop one level. At level 1 the next node either holds the key or proves it absent. Insertion runs the same search, remembering the last node visited on each level, flips coins for the new node's level, and splices it into each of those levels.
import random
class SkipList:
MAX = 32
def __init__(self, p=0.5):
self.p, self.level = p, 1
self.head = [None, [None] * SkipList.MAX] # a node: [key, forward pointers]
def search(self, key):
x = self.head
for i in reversed(range(self.level)): # from the top level down
while x[1][i] is not None and x[1][i][0] < key:
x = x[1][i] # move right
x = x[1][0]
return x is not None and x[0] == key
def insert(self, key): # keys assumed distinct
update, x = [self.head] * SkipList.MAX, self.head
for i in reversed(range(self.level)):
while x[1][i] is not None and x[1][i][0] < key:
x = x[1][i]
update[i] = x # the last node before key on level i
lvl = 1
while lvl < SkipList.MAX and random.random() < self.p:
lvl += 1 # one more level with probability p
self.level = max(self.level, lvl)
node = [key, [None] * lvl]
for i in range(lvl): # splice into levels 1 .. lvl
node[1][i], update[i][1][i] = update[i][1][i], nodeDeletion is the mirror image: search with update, then unlink the node on each of its levels. Tested, with deletion, against a sorted Python list over thousands of random operations.
With , how many forward pointers does a node have on average?
Show the answer
1.33
A node's level satisfies , so its expected number of pointers is ; with it is 2. Expected space is therefore for any constant . Our simulation with keys measured 1.333 and 2.003.
The expected search cost, by backward analysis
Reverse the path: start from where the search ends on level 1 and walk back up and to the left toward the header. On level the forward search moved right only through nodes of level exactly , and came down at a node of level above . So at each node of the reversed path, on level , the path goes up if the node's level exceeds and left otherwise. All we know about the node is that its level is at least , and since levels are independent and geometric:
Climbing to level . Each step goes up with probability , independently of the past, so each of the climbs from level 1 to level takes steps in expectation, the climb itself included (reaching the header earlier only helps):
Above level . The left moves are at most the number of keys of level at least , and the up moves at most the height minus . With :
Add the three parts:
| Keys | Average moves (simulation) | Bound | |
|---|---|---|---|
| 1/2 | 19.2 | 22.0 | |
| 1/2 | 32.2 | 34.0 | |
| 1/4 | 18.3 | 21.3 | |
| 1/4 | 31.6 | 33.3 |
High probability, and choosing p
Height. One node's level exceeds with probability , so a union bound over the nodes gives, for :
Moves. On the reversed path, each step is an independent fair coin flip (up or left) until the path reaches the header, after which it only climbs, at most more moves. If the height is at most , the random part ends after at most ups. So more than moves require fewer than heads among flips. With the expected number of heads is , and a Chernoff bound gives
Add the two failure probabilities; :
| Pointers per node, | Search bound per , | |
|---|---|---|
| 2 | 2 | |
| 1.58 | 1.88, the minimum | |
| 1.33 | 2 | |
| 1.14 | 2.67 | |
| 1.07 | 4 |
A skip list switches from to . What does the analysis predict?
- Searches become about twice as fast, since there are half as many levels
- The expected pointers per node fall from 2 to , while the leading term of the search bound stays
- Searches become about twice as slow, since each level is twice as long
- Nothing changes: affects neither space nor time
Show the answer
B. The expected pointers per node fall from 2 to , while the leading term of the search bound stays
There are half as many levels, , but each level costs twice as many expected moves, instead of 2, so the product is either way. The space falls from to pointers per node. Our simulation measured 32.2 moves with and 31.6 with , for keys.
Skip lists in practice, and the frontier
| Ordered map | Guarantee per operation | Restructuring | Concurrency |
|---|---|---|---|
| skip list | expected, and with high probability | none: levels are fixed at insertion | lock-free versions are standard |
| treap (random priorities) | expected | rotations | harder: rotations move whole subtrees |
| red-black or AVL tree | worst case | rotations and recoloring | hard: repairs can climb toward the root |
| B-tree | block reads, worst case | node splits and merges | latch-based protocols, as in databases |
Deterministic skip lists. Munro, Papadakis and Sedgewick (1992) replaced the coin flips by a rule: between any two consecutive nodes that reach level there are one, two or three nodes of level exactly . Such 1-2-3 skip lists correspond to 2-3-4 trees and guarantee search and update in the worst case.
Ranks. Store with each forward pointer the number of level-1 nodes it jumps over, its span. A search that adds up the spans it crosses learns the rank of the key it finds, and descending by spans finds the key of rank , in the same expected time. Redis keeps such spans in its sorted sets to answer rank queries.
Concurrency. In a lock-free skip list (Fraser, 2004; Herlihy & Shavit), an insertion becomes part of the set the moment a single compare-and-swap links it into the level-1 list; its higher links are added afterwards and only speed up searches. A deletion first marks the node's pointers, so that no thread links anything after it, and then unlinks it level by level. Java's ConcurrentSkipListMap (since Java 6) is a skip list of this kind, and the in-memory tables of LevelDB and RocksDB are skip lists as well.
Key takeaways
- A skip list keeps sorted linked lists on several levels, with each node's level drawn from a geometric distribution with parameter ; search moves right while the next key is smaller and drops a level otherwise.
- Backward analysis gives an expected search cost of at most moves, (that is, for ), and the expected space is pointers.
- The height exceeds with probability at most , and searches are with high probability; and give the same leading search constant, but uses fewer pointers.
- Without rotations, updates stay local, which makes skip lists the standard basis for lock-free ordered maps; deterministic 1-2-3 skip lists and indexable skip lists add worst-case bounds and rank queries.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the backward analysis of a skip-list search, why does each step of the reversed path go up with probability exactly ?
- Because the search compares keys, and a comparison succeeds with probability
- Because a node on the path at level is known only to have level at least , and with independent geometric levels
- Because exactly a fraction of the nodes on each level have a pointer one level up
- Because the header node has level
Show the answer
B. Because a node on the path at level is known only to have level at least , and with independent geometric levels
The forward search came down at a node exactly when that node's level exceeds the current level. Levels are chosen independently of the keys and of each other, and the geometric distribution is memoryless, so given that a node reaches level , it reaches with probability .
A skip list with holds keys. What is the expected total number of forward pointers in its nodes?
Show the answer
B.
Each node has pointers on average, so in total: linear space, like a doubly linked list. Only a few nodes are tall, and tall nodes are exponentially rare.
Why is the height of a skip list with at most with probability at least ?
- Because insertion rebalances the levels whenever the height exceeds
- Because a level is never more than one above the previous maximum
- Because each node exceeds level with probability , and a union bound over the nodes gives , which is for
- Because the levels of the nodes are not independent
Show the answer
C. Because each node exceeds level with probability , and a union bound over the nodes gives , which is for
for one node; by the union bound, the probability that any of the nodes exceeds is at most . With and , that is : the height exceeds with polynomially small probability.
Why are skip lists a popular basis for concurrent ordered maps, such as Java's ConcurrentSkipListMap?
- Because their searches are faster than those of balanced trees
- Because an update changes only a few pointers near the affected key, with no rotations that restructure the paths through the root, so lock-free versions need just one compare-and-swap per level
- Because skip lists never need to allocate memory
- Because their height is fixed, so threads never wait
Show the answer
B. Because an update changes only a few pointers near the affected key, with no rotations that restructure the paths through the root, so lock-free versions need just one compare-and-swap per level
Locality of updates is the point. A lock-free insertion becomes visible with a single compare-and-swap on the level-1 list, and the express links added afterwards only speed up searches. Rebalancing rotations in a tree touch nodes high up that every thread traverses, which is far harder to make lock-free.
Further reading
- W. Pugh, "Skip lists: a probabilistic alternative to balanced trees," Communications of the ACM 33(6) (1990), 668–676.
- J. I. Munro, T. Papadakis & R. Sedgewick, "Deterministic skip lists," Proceedings of SODA (1992).
- R. Motwani & P. Raghavan, Randomized Algorithms (Cambridge University Press, 1995).
- M. Herlihy, N. Shavit, V. Luchangco & M. Spear, The Art of Multiprocessor Programming, 2nd ed. (Morgan Kaufmann, 2020), the chapter on skip lists.