Sub topic 6
Inserting a Key with an Update Array
This chapter assumes you know how a skip list searches from the top layer down, and that you can splice a node into a singly linked list. It also assumes you have seen the geometric level generator from the previous chapter.
The problem insertion has to solve
A skip list node with height h sits in h linked lists at once. Inserting it means splicing it into each of those lists. Each splice needs the node that comes just before the new key in that layer, which is the predecessor.
The search already visits those predecessors. On each layer, the search stops at the last node whose key is smaller than the target, then drops down. If you record that node for every layer, you have everything the splice needs. That record is the update array.
The update array
update[i] holds the last node on layer i whose key is less than the new key. Layers above the current list height have no search step, so they default to the head sentinel. The head has MAX_LEVEL pointers, so this default works.
The insert method
This listing runs as shown.
import random
class Node:
__slots__ = ("key", "forward")
def __init__(self, key, level):
self.key = key
self.forward = [None] * level
class SkipList:
MAX_LEVEL = 16
P = 0.5
def __init__(self):
self.head = Node(None, self.MAX_LEVEL)
self.level = 1
def _random_level(self):
level = 1
while level < self.MAX_LEVEL and random.random() < self.P:
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.forward[i] is not None and node.forward[i].key < key:
node = node.forward[i]
update[i] = node
return update
def insert(self, key):
update = self._find_predecessors(key)
nxt = update[0].forward[0]
if nxt is not None and nxt.key == key:
return False
lvl = self._random_level()
if lvl > self.level:
self.level = lvl
new = Node(key, lvl)
for i in range(lvl):
new.forward[i] = update[i].forward[i]
update[i].forward[i] = new
return True
def keys_by_layer(self):
layers = []
for i in range(self.level):
row, node = [], self.head.forward[i]
while node is not None:
row.append(node.key)
node = node.forward[i]
layers.append(row)
return layers
sl = SkipList()
for k in [3, 1, 4, 15, 9, 2, 6]:
sl.insert(k)
print(sl.insert(4))
for i, row in reversed(list(enumerate(sl.keys_by_layer()))):
print(i, row)Heights are random, so the upper rows differ between runs. Layer 0 always prints [1, 2, 3, 4, 6, 9, 15], and every higher layer is a sorted subset of the layer below it.
Walking through the splice
Suppose layer 0 holds 1 → 3 → 4 → 9 and you insert 6 with height 2. The search leaves update[0] at node 4. If node 3 is the last node below 6 on layer 1, then update[1] is node 3.
For each layer the new node copies the predecessor's forward pointer, then the predecessor points to the new node. The order matters. If you overwrite update[i].forward[i] first, you lose the rest of that layer.
Common errors
- Skipping the duplicate check. This version stores unique keys. The check reads
update[0].forward[0], the first node at or after the key on layer 0. - Not raising
self.level. If the new height exceeds the current one, updateself.levelbefore the splice. Otherwise later searches never start high enough to see the new node's upper pointers. - Building
updatetoo small. A list of lengthself.levelfails when the new height is larger. Size it toMAX_LEVEL, filled with the head. - Off-by-one between height and index. A node of height
huses indexes0toh - 1. Looping tohraisesIndexError. - Choosing the height before the search. This works, but a duplicate then wastes a random call. Checking first is cleaner.
Exercise
A skip list currently has level 3. You insert a key whose random height is 5. What are update[3] and update[4], and why is it safe to use them?
Show answer
Both are the head sentinel. The search only walks layers 0 to 2, so layers 3 and 4 keep their default value. The new node becomes the first node on those layers, so the head is its correct predecessor. The head has MAX_LEVEL pointers, so head.forward[3] and head.forward[4] exist and start as None.