Design Skiplist Problem
Description
LeetCode Problem 1206.
Design a Skiplist without using any built-in libraries.
A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists.
For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:

Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons
You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).
See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list
Implement the Skiplist class:
Skiplist()Initializes the object of the skiplist.bool search(int target)Returnstrueif the integertargetexists in the Skiplist orfalseotherwise.void add(int num)Inserts the valuenuminto the SkipList.bool erase(int num)Removes the valuenumfrom the Skiplist and returnstrue. Ifnumdoes not exist in the Skiplist, do nothing and returnfalse. If there exist multiplenumvalues, removing any one of them is fine.
Note that duplicates may exist in the Skiplist, your code needs to handle this situation.
Example 1:
Input
["Skiplist", "add", "add", "add", "search", "add", "search", "erase", "erase", "search"]
[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]
Output
[null, null, null, null, false, null, true, false, true, false]
Explanation
Skiplist skiplist = new Skiplist();
skiplist.add(1);
skiplist.add(2);
skiplist.add(3);
skiplist.search(0); // return False
skiplist.add(4);
skiplist.search(1); // return True
skiplist.erase(0); // return False, 0 is not in skiplist.
skiplist.erase(1); // return True
skiplist.search(1); // return False, 1 has already been erased.
Constraints:
0 <= num, target <= 2 * 10^4- At most
5 * 10^4calls will be made tosearch,add, anderase.
Solution
Approach: Multi-Level Linked Lists with Random Heights
A skiplist is a sorted linked list with express lanes. Level 0 links all values in order. Each node is also on level 1 with probability 1/2, on level 2 with probability 1/4, and so on. A search can skip far ahead on a high level, then drop down a level when the next node would overshoot. The expected number of steps is O(log n).
Each node stores its value and an array next, where next[i] is the following node on level i. A sentinel head with value -1 (all real values are >= 0) has the maximum height 16, enough for 5 * 10^4 values. We also track level, the number of levels in use.
All three operations use one helper: on level i, walk right while the next value is smaller than the target. Doing this from the top level down to level 0 ends at the last node before the target on every level.
- search(target): walk down to level 0; the target exists if the next node on level 0 holds it.
- add(num): pick a random height (flip coins: keep growing while heads, up to
16). Walk down from the top. On each level below the new height, splice the new node in right after the node where the walk stopped. Duplicates are fine: the new copy goes before the existing equal values. - erase(num): walk down the same way. On every level where the next node holds
num, unlink it. Return whether anything was unlinked, then drop empty top levels.
With duplicates, erase might unlink one copy on the upper levels and a different copy on the lower levels. The lists stay valid anyway: on each level the first copy of num is unlinked, and level 0 loses exactly one copy, which is all the problem asks.
Complexity: O(log n) expected time for each operation, and O(n) expected space.
import random
class SkipNode:
__slots__ = ("val", "next")
def __init__(self, val: int, height: int):
self.val = val
self.next = [None] * height # next[i] is the following node on level i
class Skiplist:
MAX_LEVEL = 16 # 2^16 > 5 * 10^4 nodes
P = 0.5 # chance that a node also appears one level higher
def __init__(self):
self.head = SkipNode(-1, self.MAX_LEVEL) # sentinel before every value
self.level = 1 # levels in use
def _last_before(self, node: SkipNode, i: int, target: int) -> SkipNode:
"""Walk right on level i while the next value is smaller than target."""
while node.next[i] is not None and node.next[i].val < target:
node = node.next[i]
return node
def search(self, target: int) -> bool:
node = self.head
for i in range(self.level - 1, -1, -1): # from the top level down
node = self._last_before(node, i, target)
node = node.next[0]
return node is not None and node.val == target
def add(self, num: int) -> None:
height = 1
while height < self.MAX_LEVEL and random.random() < self.P:
height += 1
self.level = max(self.level, height)
new = SkipNode(num, height)
node = self.head
for i in range(self.level - 1, -1, -1):
node = self._last_before(node, i, num)
if i < height: # link the new node in on every level it reaches
new.next[i] = node.next[i]
node.next[i] = new
def erase(self, num: int) -> bool:
found = False
node = self.head
for i in range(self.level - 1, -1, -1):
node = self._last_before(node, i, num)
if node.next[i] is not None and node.next[i].val == num:
node.next[i] = node.next[i].next[i] # unlink on this level
found = True
while self.level > 1 and self.head.next[self.level - 1] is None:
self.level -= 1 # drop empty top levels
return found