I'm now zeroing in on the architecture of the Skip List. I've got the basic operations figured out. I am currently considering insertion complexity, and how to balance probabilistic levels effectively for performance. Thinking about how level probabilities affect worst-case scenarios is central.
Elaborating Skip List Details
I'm now fully immersed in the core mechanics. I'm focusing on implementation, considering the "subway system" analogy as a guide. Thinking about node structure, the head/sentinel node, and how level probabilities affect skip distances. I am working through the components now.
Structuring Skip List Elements
I'm solidifying the key components now. I'm focusing on the Node class design, including key, and the forward pointer array. Also, I'm defining the SkipList class, with MAX_LEVEL and P constants. I'm working through the search algorithm step by step, which involves starting at the head and moving right and down. I'm thinking about recording the search path, which will be critical for inserting new nodes.
Finalizing Insertion & Deletion
The insertion and deletion algorithms are now fully fleshed out. I'm focusing on the update[] array now, crucial for efficient pointer adjustments during both operations. I've broken insertion down into steps: locating the insertion point, determining the new node's level, and finally, linking the new node into the list. For deletion, I've got steps to locate the node, confirm its presence, relink pointers, and handle level adjustments if the top-level node is removed. Finally, I’ve decided on Python for implementation.
Analyzing Probability Impact
I'm now carefully examining the probability factor, and random.random() seems perfectly suited for the level assignment. I'm focusing on how the probabilistic level assignments impact both time and space complexities. I also want to clarify the edge cases, and think about visual examples and self-correction, e.g. dealing with duplicate keys, and how to define MAX_LEVEL. I am considering how edge cases impact the update array.
Organizing Final Content
My focus is shifting to structuring the final output. I'm solidifying the structure into conceptual overview, high-level class design, Python implementation, operation explanations, and complexity analyses. I will begin writing the detailed content to reflect the completed design process.
Here is a complete design and implementation of a Skip List.
1. Conceptual Overview
A Skip List is a probabilistic data structure that allows O(logn) search complexity, comparable to balanced binary search trees (like AVL or Red-Black trees), but is much simpler to implement.
It consists of multiple layers of sorted linked lists:
Level 0 (Bottom): Contains all elements in sorted order.
Level 1 to k: Each higher level acts as an "express lane" that skips over several elements from the level below.
The "Trick": When inserting a new node, we flip a coin to decide how tall that node should be.
Start at Level 3. Next is 19 (Too big). Go down to Level 2.
At Level 2. Next is 6 (Smaller than 12). Move to 6.
At Node 6, Level 2. Next is 19 (Too big). Go down to Level 1.
At Node 6, Level 1. Next is 9 (Smaller than 12). Move to 9.
At Node 9, Level 1. Next is 19 (Too big). Go down to Level 0.
At Node 9, Level 0. Next is 12. Found it!
3. Python Implementation
Here is a clean implementation in Python.
python
4. Operations Detail
The update array
In both Insert and Delete, you will see an array called update. This is crucial.
Because we are coming from the top down, we need to remember "Who pointed to the target?" at every specific level.
If we insert a node at Level 2, we need to change the next pointer of the node at Level 2 that comes before our new node. The update array stores these predecessor nodes.
Insertion Logic
Traverse from top to bottom. Record the path (predecessors) in update[].
Determine new_level via coin flips.
Create the Node.
Loop from 0 to new_level: Splice the node in using standard linked list insertion logic (new.next = prev.next, prev.next = new).
Deletion Logic
Traverse and Record path in update[].
Check if the node at Level 0 is mostly actually the target.
Loop upwards from 0: If update[i] points to the target, reroute it to target.next. Usually, check if update[i].forward[i] != target: break to stop early if the target doesn't extend to that level.
Shrink Height: If the deleted node was the only node at the highest level, decrement the list's currentLevel.
5. Complexity Analysis
Metric
Complexity
Explanation
Search Time
O(logn) (Expected)
We skip half the remaining elements roughly every level we ascend. This mimics binary search.
Insert Time
O(logn) (Expected)
Determining the position is O(, finding the random level is , updating pointers is proportional to the level height (logarithmic).
Worst Case:
In the extremely rare event that the random number generator produces the maximum level for every node (or level 0 for every node), operations degrade to O(n). However, with a good RNG, the probability of this is negligible.
import random
class Node:
def __init__(self, key, level):
self.key = key
# Array to hold pointers to the next nodes at different levels
# forward[i] points to the next node at level i
self.forward = [None] * (level + 1)
class SkipList:
def __init__(self, max_level=16, p=0.5):
self.MAX_LEVEL = max_level
self.P = p # Probability of increasing level
self.header = Node(-1, self.MAX_LEVEL) # Sentinel node
self.level = 0 # Current highest level in the list
def random_level(self):
"""
Randomly determines the level for a new node.
Conceptually similar to flipping a coin.
"""
lvl = 0
while random.random() < self.P and lvl < self.MAX_LEVEL:
lvl += 1
return lvl
def search(self, target):
"""
Checks if a target key exists in the Skip List.
Time: O(log n)
"""
current = self.header
# Start from the top level and move down
for i in range(self.level, -1, -1):
# Move forward while the next node is less than target
while current.forward[i] and current.forward[i].key < target:
current = current.forward[i]
# We are now at level 0, just before the target position
current = current.forward[0]
# Verification
if current and current.key == target:
return True
return False
def insert(self, key):
"""
Inserts a new key into the Skip List.
Time: O(log n)
"""
# update[] will store the node preceding the insertion point
# at every level.
update = [None] * (self.MAX_LEVEL + 1)
current = self.header
# 1. Locate insertion points at all levels
for i in range(self.level, -1, -1):
while current.forward[i] and current.forward[i].key < key:
current = current.forward[i]
update[i] = current
# 2. Determine the random level for the new node
lvl = self.random_level()
# If random level is higher than current list level,
# initialize update array for the new higher levels
if lvl > self.level:
for i in range(self.level + 1, lvl + 1):
update[i] = self.header
self.level = lvl
# 3. Create and link the new node
new_node = Node(key, lvl)
for i in range(lvl + 1):
new_node.forward[i] = update[i].forward[i]
update[i].forward[i] = new_node
print(f"Inserted: {key} at level {lvl}")
def delete(self, key):
"""
Deletes a key from the Skip List.
Time: O(log n)
"""
update = [None] * (self.MAX_LEVEL + 1)
current = self.header
# 1. Locate the node to delete (record paths)
for i in range(self.level, -1, -1):
while current.forward[i] and current.forward[i].key < key:
current = current.forward[i]
update[i] = current
# Move to target node at level 0
target_node = current.forward[0]
# 2. If node exists, verify and remove
if target_node and target_node.key == key:
# Start from bottom, remove links up to the node's height
for i in range(self.level + 1):
# If the updated node's forward pointer isn't our target,
# we are done (target didn't exist at this high of a level)
if update[i].forward[i] != target_node:
break
update[i].forward[i] = target_node.forward[i]
# 3. Clean up levels
# If we deleted the highest node, reduce the list level
while self.level > 0 and self.header.forward[self.level] is None:
self.level -= 1
print(f"Deleted: {key}")
else:
print(f"Key {key} not found for deletion")
def display(self):
"""Helper to visualize the list structure"""
print("\n--- Skip List ---")
for i in range(self.level, -1, -1):
node = self.header.forward[i]
print(f"Level {i}: ", end=" ")
while node:
print(f"{node.key} -> ", end=" ")
node = node.forward[i]
print("NULL")
print("-----------------")
# Driver Code to test
sl = SkipList()
sl.insert(3)
sl.insert(6)
sl.insert(7)
sl.insert(9)
sl.insert(12)
sl.insert(19)
sl.insert(17)
sl.display()
print(f"Search 19: {sl.search(19)}") # True
print(f"Search 10: {sl.search(10)}") # False
sl.delete(19)
sl.display()
log
n
)
O(1)
Delete Time
O(logn) (Expected)
Similar to insert; find the predecessor, update pointers.
Space
O(n) (Expected)
Level 0 has n nodes. Level 1 has n/2. Level 2 has n/4. Comparing this to a geometric series ∑2in=2n. The average node has 2 pointers.