Sub topic 7
Deleting a key and shrinking the list
This chapter assumes you have read the earlier chapters on search and insertion. You should know how the update array records the last node visited on each layer, and you should be comfortable with singly linked list pointer splicing and basic Python.
The idea
Deletion mirrors insertion. You run the same search, collect the predecessor of the key on every layer, and then unlink the target node from each layer where it appears. After that, you check whether the top layers have become empty and lower the list's level if they have.
Unlike a balanced tree, a skip list does no rebalancing on delete. The node's height was fixed by coin flips when it was inserted, and removing it leaves the other nodes' heights untouched.
The delete method
Here is the method from the full implementation.
def delete(self, key):
update = self._find_predecessors(key)
target = update[0].forward[0]
if target is None or target.key != key:
return False
for i in range(self.level):
if update[i].forward[i] is not target:
break
update[i].forward[i] = target.forward[i]
while self.level > 1 and self.head.forward[self.level - 1] is None:
self.level -= 1
return TrueThe method has four steps.
- Find predecessors.
_find_predecessors(key)returnsupdate, whereupdate[i]is the last node on layeriwhose key is less thankey. - Confirm the key exists. The candidate is
update[0].forward[0], the next node on the bottom layer. If it is missing or has a different key, nothing is deleted and the method returnsFalse. - Splice it out. For each layer from 0 upward, make the predecessor point to whatever the target pointed to.
- Shrink the list. Lower
self.levelwhile the highest layer has no nodes.
Why the loop breaks early
A node of height h appears on layers 0 to h - 1. On any layer above that, update[i].forward[i] is some other node, or None. The check update[i].forward[i] is not target detects this, and the loop stops. Because heights are contiguous from the bottom, once the target is missing from one layer it is missing from every higher layer.
Compare with is not, not with key. Identity is the right test because you want to know whether this exact node is linked on that layer.
Shrinking the list
The level attribute tells search where to start. If the tallest node is deleted, the layers it occupied may now be empty. Searching those layers costs a wasted step each. The while loop checks self.head.forward[self.level - 1]. If the head has no successor on the top layer, that layer is empty and level drops by one. The loop repeats until it reaches a non-empty layer or layer 1.
The loop never goes below 1, so the bottom layer always exists, even in an empty list. The head keeps all MAX_LEVEL pointers regardless, so no memory is freed on the head.
A worked trace
Suppose the list holds 1, 2, 3, 4, 6, 9, 15, and key 4 has height 3. The predecessors of 4 are the nodes for 3 (layer 0), 2 (layer 1), and 1 (layer 2).
Step by step, the loop does the following:
- Layer 0: the node for 3 points at 4, so it is set to point at 6.
- Layer 1: the node for 2 points at 4, so it is set to point at 4's layer 1 successor.
- Layer 2: the node for 1 points at 4, so it is set to 4's layer 2 successor.
- Layer 3:
update[3].forward[3]is not the target, so the loop breaks.
You can check the result with the example from the earlier chapter.
sl = SkipList()
for k in [3, 1, 4, 15, 9, 2, 6]:
sl.insert(k)
print(sl.delete(4)) # True
print(sl.contains(4)) # False
print(sl.delete(4)) # False, already gone
print(sl.delete(100)) # False, never presentCommon errors
- Deleting on the bottom layer only. Upper layers keep pointers to a removed node, and later searches may land on it.
- Looping over
MAX_LEVELwithout the early break. Predecessors on layers above the node's height would be rewired incorrectly, becauseupdate[i].forward[i]is not the target. - Comparing keys instead of identity in the splice check. This works for unique keys but breaks if you later allow duplicates.
- Letting
levelfall to 0. An empty list needs level 1 so thatrange(self.level - 1, -1, -1)still visits layer 0.
The cost of delete is the same as search plus one pass over at most level layers, so it is expected O(log n).
Exercise
After deleting the only node of height 5 from a list whose other nodes all have height 2 or less, what happens to self.level, and why does delete need the while loop rather than a single decrement?
Show answer
self.level drops to 2, the new tallest height. Layers 3 to 5 are all empty, so the head has no successor on each of them. The loop must repeat to skip every empty layer, not just one. A single decrement would leave level at 4 and searches would start on empty layers.
Exercise
Why does delete return False without changing any pointers when the key is absent?
Show answer
The candidate update[0].forward[0] is either None or has a different key. Splicing would then unlink a node that does not match the key, so the method returns before the loop.