Sub topic 9
Skip lists as a probabilistic alternative
This chapter assumes you know Big-O notation, linked lists, binary search, and the ordered map operations from earlier chapters (floor, ceiling, range views).
The idea
A balanced binary search tree keeps its shape with rotations. A skip list gets the same O(log n) expected cost with a different mechanism: it stacks several sorted linked lists on top of each other and uses random numbers to decide how tall each element is.
The bottom level holds every key in sorted order. Each higher level holds a random subset of the level below, so it works as an express lane. A search starts in the sparsest lane at the top, moves right while the next key is still smaller than the target, then drops down a level and repeats.
How heights are chosen
When you insert a key, you flip a coin until it comes up tails. The number of heads sets the node's height. Half of the nodes reach level 1, a quarter reach level 2, and so on. With probability 1/2 per level, the expected number of levels is about log2(n).
No rebalancing is needed. The structure is balanced in expectation, and a bad shape would require an extremely unlikely run of coin flips.
A working implementation
import random
class Node:
def __init__(self, key, value, level):
self.key = key
self.value = value
self.next = [None] * level
class SkipList:
MAX_LEVEL = 16
def __init__(self):
self.head = Node(None, None, self.MAX_LEVEL)
self.level = 1
def _random_level(self):
level = 1
while level < self.MAX_LEVEL and random.random() < 0.5:
level += 1
return level
def _find_predecessors(self, key):
update = [self.head] * self.MAX_LEVEL
node = self.head
for i in range(self.level - 1, -1, -1):
while node.next[i] and node.next[i].key < key:
node = node.next[i]
update[i] = node
return update
def get(self, key):
node = self._find_predecessors(key)[0].next[0]
return node.value if node and node.key == key else None
def ceiling(self, key):
node = self._find_predecessors(key)[0].next[0]
return node.key if node else None
def put(self, key, value):
update = self._find_predecessors(key)
node = update[0].next[0]
if node and node.key == key:
node.value = value
return
new_level = self._random_level()
self.level = max(self.level, new_level)
new = Node(key, value, new_level)
for i in range(new_level):
new.next[i] = update[i].next[i]
update[i].next[i] = new
sl = SkipList()
for k in [30, 10, 50, 20, 40]:
sl.put(k, str(k))
print(sl.get(20)) # 20
print(sl.ceiling(35)) # 40The descent that finds the predecessors on every level is shared by get, ceiling and put. A range scan works the same way: find the first key at or above the lower bound, then follow level-0 links until you pass the upper bound.
Trade-offs against balanced trees
| Aspect | Skip list | Red-black or AVL tree |
|---|---|---|
| Search, insert, delete | O(log n) expected | O(log n) worst case |
| Range scan | Follows level-0 links | In-order traversal |
| Rebalancing code | None | Rotations, hard to write |
| Memory | About 2 pointers per node on average | 2 child pointers plus a balance field |
| Concurrency | Easier to make lock-free | Rotations touch many nodes |
The concurrency row is the main reason skip lists are used in practice. An insert only changes the pointers of a few neighbouring nodes, so it can be done with compare-and-swap operations. Java's ConcurrentSkipListMap is built this way. Redis sorted sets also use a skip list.
The weaknesses are that the O(log n) bound is only probabilistic, that pointer-heavy nodes cache poorly, and that results depend on the quality of the random number generator.
Common mistakes
- Using a fixed height cap that is too small for your data. With p = 1/2, a cap of 16 suits up to about 65,000 keys. Use a larger cap for bigger sets.
- Forgetting to update the list's current level when a new node is taller than the current maximum.
- Skipping the equality check after the descent, which creates duplicate keys.
Exercise
In the implementation above, why does put compute update (the predecessor at every level) before creating the new node?
Show answer
Linking the new node into level i requires the node just before the insertion point on that level, so the new node's pointer can copy that predecessor's old next pointer and the predecessor can then point to the new node. The descent from the top finds all of these predecessors in one pass.