Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Skip Lists

Randomized express lanes: expected O(log n) search in a linked list.

A sorted linked list needs about n/2n/2 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 2log⁡2n2\log_2 n 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 L/p+1/(1−p)L/p + 1/(1-p), with L=log⁡1/pnL = \log_{1/p} n, by backward analysis, and the expected O(n)O(n) space.
  • Show that the height and the search cost are O(log⁡n)O(\log n) with high probability, and choose pp.
  • 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.

python
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], node

Deletion 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.

Predict before you look

With p=14p = \tfrac14, how many forward pointers does a node have on average?

Show the answer

1.33

A node's level ℓ\ell satisfies P(ℓ≥i)=p i−1P(\ell \ge i) = p^{\,i-1}, so its expected number of pointers is ∑i≥1p i−1=11−p=43≈1.33\sum_{i \ge 1} p^{\,i-1} = \tfrac{1}{1-p} = \tfrac43 \approx 1.33; with p=12p = \tfrac12 it is 2. Expected space is therefore O(n)O(n) for any constant pp. Our simulation with 2162^{16} keys measured 1.333 and 2.003.

The expected search cost, by backward analysis

DerivationProof: walk the search path backward
  1. P(up)  =  P(ℓ≥i+1 ∣ ℓ≥i)  =  p,P(left)  =  1−pP\big(\text{up}\big) \;=\; P\big(\ell \ge i + 1 \,\big|\, \ell \ge i\big) \;=\; p, \qquad P\big(\text{left}\big) \;=\; 1 - p

    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 ii the forward search moved right only through nodes of level exactly ii, and came down at a node of level above ii. So at each node of the reversed path, on level ii, the path goes up if the node's level exceeds ii and left otherwise. All we know about the node is that its level is at least ii, and since levels are independent and geometric:

  2. E[steps below level L]  ≤  L−1pE[\text{steps below level } L] \;\le\; \frac{L - 1}{p}

    Climbing to level LL. Each step goes up with probability pp, independently of the past, so each of the L−1L - 1 climbs from level 1 to level LL takes 1/p1/p steps in expectation, the climb itself included (reaching the header earlier only helps):

  3. E[left]  ≤  n pL−1=1p,E[up]  ≤  ∑k≥1P(height≥L+k)  ≤  ∑k≥1n pL+k−1  =  11−pE[\text{left}] \;\le\; n\,p^{L-1} = \frac1p, \qquad E[\text{up}] \;\le\; \sum_{k \ge 1} P\big(\text{height} \ge L + k\big) \;\le\; \sum_{k \ge 1} n\,p^{L+k-1} \;=\; \frac{1}{1-p}

    Above level LL. The left moves are at most the number of keys of level at least LL, and the up moves at most the height minus LL. With n pL=1n\,p^{L} = 1:

  4. E[moves]  ≤  L−1p+1p+11−p  =  Lp+11−pE[\text{moves}] \;\le\; \frac{L - 1}{p} + \frac{1}{p} + \frac{1}{1-p} \;=\; \frac{L}{p} + \frac{1}{1-p}

    Add the three parts:

KeysppAverage moves (simulation)Bound L/p+1/(1−p)L/p + 1/(1-p)
2102^{10}1/219.222.0
2162^{16}1/232.234.0
2102^{10}1/418.321.3
2162^{16}1/431.633.3
Our simulation: 5 random skip lists of each size, 2,000 searches for stored keys in each (all of them for 2102^{10} keys). The bound is close to the truth.

High probability, and choosing p

DerivationProof sketch
  1. P(height>h)  ≤  n 2−h  =  n1−cP(\text{height} > h) \;\le\; n\,2^{-h} \;=\; n^{1-c}

    Height. One node's level exceeds hh with probability 2−h2^{-h}, so a union bound over the nn nodes gives, for h=clog⁡2nh = c\log_2 n:

  2. P(Bin⁡(m,12)<h)  ≤  e−(3/4)22⋅4h  =  e−98clog⁡2n  ≤  n1−cP\big(\operatorname{Bin}(m, \tfrac12) < h\big) \;\le\; e^{-\frac{(3/4)^2}{2}\cdot 4h} \;=\; e^{-\frac98 c\log_2 n} \;\le\; n^{1-c}

    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 hh more moves. If the height is at most hh, the random part ends after at most hh ups. So more than m+hm + h moves require fewer than hh heads among mm flips. With m=8clog⁡2nm = 8c\log_2 n the expected number of heads is 4h4h, and a Chernoff bound gives

  3. P(moves>9clog⁡2n)  ≤  P(height>h)+P(Bin⁡(m,12)<h)  ≤  2n1−cP\big(\text{moves} > 9c\log_2 n\big) \;\le\; P(\text{height} > h) + P\big(\operatorname{Bin}(m, \tfrac12) < h\big) \;\le\; 2n^{1-c}

    Add the two failure probabilities; m+h=9clog⁡2nm + h = 9c\log_2 n:

ppPointers per node, 11−p\tfrac{1}{1-p}Search bound per log⁡2n\log_2 n, 1plog⁡2(1/p)\tfrac{1}{p\log_2(1/p)}
1/21/222
1/e≈0.371/e \approx 0.371.581.88, the minimum
1/41/41.332
1/81/81.142.67
1/161/161.074
The leading term of the search bound is L/p=log⁡2n / (plog⁡2(1/p))L/p = \log_2 n\,/\,(p\log_2(1/p)). It is smallest at p=1/ep = 1/e, and the same for p=12p = \tfrac12 and p=14p = \tfrac14, although 14\tfrac14 needs a third fewer pointers per node. A smaller pp makes the running time more variable, since each level is sparser and its horizontal runs are longer; Pugh suggested p=14p = \tfrac14 as a default.
Check your understanding

A skip list switches from p=12p = \tfrac12 to p=14p = \tfrac14. What does the analysis predict?

  1. Searches become about twice as fast, since there are half as many levels
  2. The expected pointers per node fall from 2 to 43\tfrac43, while the leading term of the search bound stays 2log⁡2n2\log_2 n
  3. Searches become about twice as slow, since each level is twice as long
  4. Nothing changes: pp affects neither space nor time
Show the answer

B. The expected pointers per node fall from 2 to 43\tfrac43, while the leading term of the search bound stays 2log⁡2n2\log_2 n

There are half as many levels, log⁡4n=12log⁡2n\log_4 n = \tfrac12\log_2 n, but each level costs twice as many expected moves, 1/p=41/p = 4 instead of 2, so the product L/pL/p is 2log⁡2n2\log_2 n either way. The space falls from 1/(1−p)=21/(1-p) = 2 to 43\tfrac43 pointers per node. Our simulation measured 32.2 moves with p=12p = \tfrac12 and 31.6 with p=14p = \tfrac14, for 2162^{16} keys.

Skip lists in practice, and the frontier

Ordered mapGuarantee per operationRestructuringConcurrency
skip listO(log⁡n)O(\log n) expected, and with high probabilitynone: levels are fixed at insertionlock-free versions are standard
treap (random priorities)O(log⁡n)O(\log n) expectedrotationsharder: rotations move whole subtrees
red-black or AVL treeO(log⁡n)O(\log n) worst caserotations and recoloringhard: repairs can climb toward the root
B-treeO(log⁡Bn)O(\log_B n) block reads, worst casenode splits and mergeslatch-based protocols, as in databases
A skip list has a linked list's cache behavior, one possible miss per hop, so a B-tree usually wins on disk and often in memory. Its strengths are simplicity, local updates and concurrency.

Deterministic skip lists. Munro, Papadakis and Sedgewick (1992) replaced the coin flips by a rule: between any two consecutive nodes that reach level h+1h + 1 there are one, two or three nodes of level exactly hh. Such 1-2-3 skip lists correspond to 2-3-4 trees and guarantee O(log⁡n)O(\log n) 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 kk, in the same expected O(log⁡n)O(\log n) 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 pp; search moves right while the next key is smaller and drops a level otherwise.
  • Backward analysis gives an expected search cost of at most L/p+1/(1−p)L/p + 1/(1-p) moves, L=log⁡1/pnL = \log_{1/p} n (that is, 2log⁡2n+22\log_2 n + 2 for p=12p = \tfrac12), and the expected space is n/(1−p)n/(1-p) pointers.
  • The height exceeds clog⁡1/pnc\log_{1/p} n with probability at most n1−cn^{1-c}, and searches are O(log⁡n)O(\log n) with high probability; p=12p = \tfrac12 and p=14p = \tfrac14 give the same leading search constant, but 14\tfrac14 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.

Question 1

In the backward analysis of a skip-list search, why does each step of the reversed path go up with probability exactly pp?

  1. Because the search compares keys, and a comparison succeeds with probability pp
  2. Because a node on the path at level ii is known only to have level at least ii, and with independent geometric levels P(ℓ≥i+1∣ℓ≥i)=pP(\ell \ge i + 1 \mid \ell \ge i) = p
  3. Because exactly a fraction pp of the nodes on each level have a pointer one level up
  4. Because the header node has level log⁡1/pn\log_{1/p} n
Show the answer

B. Because a node on the path at level ii is known only to have level at least ii, and with independent geometric levels P(ℓ≥i+1∣ℓ≥i)=pP(\ell \ge i + 1 \mid \ell \ge i) = p

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 ii, it reaches i+1i + 1 with probability pp.

Question 2

A skip list with p=12p = \tfrac12 holds nn keys. What is the expected total number of forward pointers in its nodes?

  1. nn
  2. 2n2n
  3. nlog⁡2nn \log_2 n
  4. n2/2n^2/2
Show the answer

B. 2n2n

Each node has ∑i≥12−(i−1)=2\sum_{i \ge 1} 2^{-(i-1)} = 2 pointers on average, so 2n2n in total: linear space, like a doubly linked list. Only a few nodes are tall, and tall nodes are exponentially rare.

Question 3

Why is the height of a skip list with p=12p = \tfrac12 at most 2log⁡2n+12\log_2 n + 1 with probability at least 1−1/n1 - 1/n?

  1. Because insertion rebalances the levels whenever the height exceeds 2log⁡2n2\log_2 n
  2. Because a level is never more than one above the previous maximum
  3. Because each node exceeds level hh with probability 2−h2^{-h}, and a union bound over the nn nodes gives P(height>h)≤n 2−hP(\text{height} > h) \le n\,2^{-h}, which is 1/n1/n for h=2log⁡2nh = 2\log_2 n
  4. Because the levels of the nodes are not independent
Show the answer

C. Because each node exceeds level hh with probability 2−h2^{-h}, and a union bound over the nn nodes gives P(height>h)≤n 2−hP(\text{height} > h) \le n\,2^{-h}, which is 1/n1/n for h=2log⁡2nh = 2\log_2 n

P(ℓ>h)=phP(\ell > h) = p^h for one node; by the union bound, the probability that any of the nn nodes exceeds hh is at most n phn\,p^h. With p=12p = \tfrac12 and h=clog⁡2nh = c\log_2 n, that is n1−cn^{1-c}: the height exceeds clog⁡2nc\log_2 n with polynomially small probability.

Question 4

Why are skip lists a popular basis for concurrent ordered maps, such as Java's ConcurrentSkipListMap?

  1. Because their searches are faster than those of balanced trees
  2. 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
  3. Because skip lists never need to allocate memory
  4. 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.