Sub topic 11
Rank queries with spans
This chapter assumes you have read the earlier chapters on search and insertion, so you know the forward array and the update array. It adds one number to each pointer so the list can answer "what is the position of this key?" and "which key is at position k?" in expected O(log n) time.
The problem with plain skip lists
A plain skip list finds a key quickly, but it cannot tell you how many keys come before it. To get a rank you would walk the bottom layer and count, which costs O(n). The same applies to "give me the 1000th key".
An indexable skip list fixes this by storing a span with every forward pointer. The span is the number of bottom-layer steps that the pointer jumps over.
If you add the spans along any path from the head to a node, you get that node's position. The head is position 0. Both express pointers and bottom pointers give the same total, which is what makes the idea work.
Rank and index lookups
Searching for a key already walks down from the top layer. To get a rank, add up each span you follow. To find the node at position k, follow a pointer only if the distance travelled plus its span does not pass k.
The code below is a complete insert-only indexable skip list. Spans on a pointer that leads to None are never read, so they can hold any value.
import random
class Node:
__slots__ = ("key", "forward", "span")
def __init__(self, key, level):
self.key = key
self.forward = [None] * level
self.span = [0] * level
class IndexedSkipList:
MAX_LEVEL = 16
P = 0.5
def __init__(self):
self.head = Node(None, self.MAX_LEVEL)
self.level = 1
self.size = 0
def _random_level(self):
level = 1
while level < self.MAX_LEVEL and random.random() < self.P:
level += 1
return level
def insert(self, key):
update = [self.head] * self.MAX_LEVEL
rank = [0] * self.MAX_LEVEL # nodes before update[i]
node = self.head
for i in range(self.level - 1, -1, -1):
rank[i] = rank[i + 1] if i < self.level - 1 else 0
while node.forward[i] is not None and node.forward[i].key < key:
rank[i] += node.span[i]
node = node.forward[i]
update[i] = node
nxt = update[0].forward[0]
if nxt is not None and nxt.key == key:
return False
lvl = self._random_level()
if lvl > self.level:
for i in range(self.level, lvl):
rank[i] = 0
update[i] = self.head
self.head.span[i] = self.size
self.level = lvl
new = Node(key, lvl)
for i in range(lvl):
new.forward[i] = update[i].forward[i]
update[i].forward[i] = new
new.span[i] = update[i].span[i] - (rank[0] - rank[i])
update[i].span[i] = (rank[0] - rank[i]) + 1
for i in range(lvl, self.level):
update[i].span[i] += 1
self.size += 1
return True
def rank(self, key):
"""Number of keys smaller than key, or None if key is absent."""
node = self.head
travelled = 0
for i in range(self.level - 1, -1, -1):
while node.forward[i] is not None and node.forward[i].key <= key:
travelled += node.span[i]
node = node.forward[i]
if node is not self.head and node.key == key:
return travelled - 1
return None
def at(self, index):
"""Key at 0-based position index."""
if not 0 <= index < self.size:
raise IndexError(index)
target = index + 1
node = self.head
travelled = 0
for i in range(self.level - 1, -1, -1):
while node.forward[i] is not None and travelled + node.span[i] <= target:
travelled += node.span[i]
node = node.forward[i]
return node.key
sl = IndexedSkipList()
for k in [30, 10, 50, 20, 40]:
sl.insert(k)
print(sl.rank(30)) # 2
print(sl.rank(35)) # None
print(sl.at(0)) # 10
print(sl.at(4)) # 50The output is the same for every random choice of heights, because heights change only the route, not the spans' totals.
How insertion keeps spans correct
Insertion records one extra value per layer, rank[i], which is the number of keys before update[i]. The new node sits at bottom position rank[0] + 1. On each layer the new node splits an existing span in two:
- The predecessor's span becomes
rank[0] - rank[i] + 1, the distance to the new node. - The new node's span becomes the old span minus the distance to the new node.
- On layers above the new node's height, the pointer jumps over the new node, so its span grows by 1.
Deletion does the reverse. If update[i].forward[i] is the deleted node, add the node's span minus 1 to the predecessor's span and relink. Otherwise subtract 1 from the predecessor's span.
Cost
| Operation | Expected time | Extra space |
|---|---|---|
| rank(key) | O(log n) | one integer per pointer |
| at(index) | O(log n) | one integer per pointer |
| insert, delete | O(log n) | one integer per pointer |
The extra work per update is a constant amount at each layer, so the complexity matches the plain skip list. This is how Redis sorted sets answer rank queries.
Exercise
In the list from the diagram (10, 20, 30, 40, 50), you insert 25 and it gets height 1. Which spans change on the express pointers, and what are their new values?
Show answer
25 lands between 20 and 30, so it is at position 3 and 30 moves to position 4. The head-to-30 express pointer jumps over 25, so its span grows from 3 to 4. The 30-to-50 pointer is unaffected and stays 2. The bottom pointers change too: 20 to 25 has span 1, and 25 to 30 has span 1.