This is a great request to implement a skip list with probabilistic balancing. Let me design a comprehensive implementation that includes:
- Skip List Node structure
- Skip List implementation with:
- Probabilistic height determination
- Search operation O(log n)
- Insert operation O(log n)
- Delete operation O(log n)
- Proper leveling mechanism
- Detailed documentation and examples
I'll create a production-quality implementation with:
- Clear comments
- Error handling
- Time complexity analysis
- Visualization helpers
- Comprehensive test cases
Let me think through the key aspects:
- Node Structure: Each node needs to have forward pointers at multiple levels
- Height Determination: Use probability to determine tower height (typically p=0.5)
- Search: Start from top level and move forward until we find the position
- Insert: Find the position and create a new node with probabilistic height
- Delete: Find the node and remove it from all levels
The key insight is that with probabilistic height selection, we get O(log n) average time complexity with high probability.
Let me write comprehensive code:
import random
from typing import Optional, List, Any, Callable
class SkipListNode:
"""Node in the skip list with multiple forward pointers (tower)."""
def __init__(self, key: Any, value: Any, level: int):
"""
Initialize a skip list node.
Args:
key: The key to store
value: The value associated with the key
level: The height of the tower (number of levels)
"""
self.key = key
self.value = value
self.level = level
self.forward = [None] * (level + 1) # Forward pointers for each level
def __repr__(self) -> str:
return f"SkipListNode(key={self.key}, level={self.level})"
Now I need to implement the main SkipList class. This data structure uses probabilistic balancing to maintain O(log n) performance characteristics. Each node has a randomly determined height, and the search algorithm traverses from the highest level downward, moving forward until reaching the target position or determining where it should be inserted. The beauty of this approach is that we avoid the complexity of tree rotations while still achieving logarithmic time bounds with high probability.
key is less than target
while current.forward[i] is not None and current.forward[i].key < key:
current = current.forward[i]
# Move to the next node at level 0
current = current.forward[0]
# Check if we found the key
if current is not None and current.key == key:
return current.value
return None
def _search_node(self, key: Any) -> tuple[Optional[SkipListNode], List[SkipListNode]]:
"""
Internal search that returns the node and the update list.
Used by insert and delete operations.
Args:
key: The key to search for
Returns:
Tuple of (node, update_list) where:
- node is
I cannot complete this thought as the original thinking appears to be cut off mid-sentence and the next thinking provided is incomplete as well. level for new node
new_level = self._random_level()
# Extend skip list levels if the new node's level exceeds current max
if new_level > self.level:
for i in range(self.level + 1, new_level + 1):
update[i] = self.head
self.level = new_level
# Instantiate the new node with generated level
new_node = SkipListNode(key, value, new_level)
# Reconnect pointers at each level to insert the node
for i in range(new_level + 1):
new_node.forward[i] = update[i].forward[i]
update[i].forward[i] = new_node
self.size += 1
return True
def delete(self, key: Any) -> bool:
"""
Delete a key from the skip list.
Time Complexity: O(log n) average case
Args:
key: The key to delete
Returns:
True if key was found and deleted, False otherwise
"""
node, update = self._search_node(key)
# Key not found
if node is None or node.key != key:
return False
# Bypass the deleted node by updating pointers
for i in range(node.level + 1):
update[i].forward[i] = node.forward[i]
# Trim empty levels from the top
while self.level > 0 and self.head.forward[self.level] is None:
self.level -= 1
self.size -= 1
return True
def contains(self, key: Any) -> bool:
"""
Check if a key exists in the skip list.
Time Complexity: O(log n) average case
Args:
key: The key to check
Returns:
True if key exists, False otherwise
"""
return self.search(key) is not None
def range_search(self, start_key: Any, end_key: Any) -> List[tuple[Any, Any]]:
"""
Find all key-value pairs within a range.
Time Complexity: O(log n + m) where m is the number of elements in range
Args:
start_key: Start of range (inclusive)
end_key: End of range (inclusive)
Returns:
List of (key, value) tuples in the range
"""
result = []
node, _ = self._search_node(start_key)
# Advance to the first key within bounds
while node is not None and node.key < start_key:
node = node.forward[0]
# Gather all entries up to the end key
while node is not None and node.key <= end_key:
result.append((node.key, node.value))
node = node.forward[0]
return result
def get_all(self) -> List[tuple[Any, Any]]:
"""
Get all key-value pairs in sorted order.
Time Complexity: O(n)
Returns:
List of (key, value) tuples in sorted order
"""
result = []
current = self.head.forward[0]
while current is not None:
result.append((current.key, current.value))
current = current.forward[0]
return result
def __len__(self) -> int:
"""Return the number of elements in the skip list."""
return self.size
def __contains__(self, key: Any) -> bool:
"""Check if key exists using 'in' operator."""
return self.contains(key)
def __getitem__(self, key: Any) -> Any:
"""Get value using [] operator."""
value = self.search(key)
if value is None:
raise KeyError(f"Key {key} not found")
return value
def __setitem__(self, key: Any, value: Any) -> None:
"""Set value using [] operator."""
self.insert(key, value)
def __delitem__(self, key: Any) -> None:
"""Delete key using del operator."""
if not self.delete(key):
raise KeyError(f"Key {key} not found")
def visualize(self) -> str:
"""
Create a text visualization of the skip list structure.
Returns:
A string representation of the skip list structure
"""
lines = []
lines.append(f"Skip List (levels: {self.level}, size: {self.size})")
lines.append("=" * 60)
for level in range(self.level, -1, -1):
line = f"Level {level}: "
current = self.head
while current is not None:
if current == self.head:
line += "[HEAD]"
else:
line += f"[{current.key}]"
if level <= current.level and current.forward[level] is not None:
line += "->"
current = current.forward[level] if level <= current.level else None
lines.append(line)
return "\n".join(lines)
def get_statistics(self) -> dict:
"""
Get statistics about the skip list structure.
Returns:
Dictionary with structure statistics
"""
level_counts = [0] * (self.level + 1)
current = self.head.forward[0]
while current is not None:
for i in range(current.level + 1):
level_counts[i] += 1
current = current.forward[0]
return {
'size': self.size,
'max_level': self.max_level,
'current_level': self.level,
'probability': self.probability,
'level_counts': level_counts
}
import math
def test_skip_list():
"""Comprehensive test suite for the skip list."""
print("=" * 70)
print("SKIP LIST IMPLEMENTATION - COMPREHENSIVE TESTING")
print("=" * 70)
# Test 1: Basic insertion and search
print("\n[TEST 1] Basic Insertion and Search")
print("-" * 70)
sl = SkipList(max_level=8, probability=0.5)
keys = [50, 30, 70, 20, 40, 60, 80, 10, 25, 35]
for key in keys:
sl.insert(key, f"value_{key}")
print(f"Inserted {len(sl)} elements")
print(f"Skip list structure:\n{sl.visualize()}\n")
# Test search
print("Search tests:")
for key in [50, 10, 80, 15]:
result = sl.search(key)
print(f" search({key}): {result}")
# Test 2: Duplicate insertion (update)
print("\n[TEST 2] Duplicate Insertion (Value Update)")
print("-" * 70)
result = sl.insert(50, "updated_value_50")
print(f"Updated key 50: {result} (should be False)")
print(f"New value for key 50: {sl.search(50)}")
# Test 3: Range search
print("\n[TEST 3] Range Search")
print("-" * 70)
range_result = sl.range_search(25, 75)
print(f"Keys in range [25, 75]: {[k for k, v in range_result]}")
# Test 4: Deletion
print("\n[TEST 4] Deletion")
print("-" * 70)
print(f"Size before deletion: {len(sl)}")
sl.delete(30)
sl.delete(70)
print(f"Size after deleting 30 and 70: {len(sl)}")
print(f"Skip list after deletion:\n{sl.visualize()}\n")
# Test 5: All elements in order
print("\n[TEST 5] All Elements in Order")
print("-" * 70)
all_items = sl.get_all()
print(f"All items (sorted): {[(k, v) for k, v in all_items]}")
# Test 6: Statistics
print("\n[TEST 6] Statistics")
print("-" * 70)
stats = sl.get_statistics()
print(f"Size: {stats['size']}")
print(f"Current level: {stats['current_level']}")
print(f"Max level: {stats['max_level']}")
print(f"Probability: {stats['probability']}")
print(f"Nodes at each level: {stats['nodes_at_level']}")
print(f"Theoretical height: {stats['theoretical_height']}")
# Test 7: Large dataset with time complexity analysis
print("\n[TEST 7] Large Dataset with Time Complexity Analysis")
print("-" * 70)
import time
sizes = [100, 1000, 10000]
for size in sizes:
sl_test = SkipList(max_level=20, probability=0.5)
# Insert random elements
start = time.time()
for i in range(size):
sl_test.insert(random.randint(0, size * 10), f"value_{i}")
insert_time = time.time() - start
# Search for random elements
start = time.time()
for _ in range(size):
sl_test.search(random.randint(0, size * 10))
search_time = time.time() - start
I cannot complete this thought as the next thinking appears to be cut off mid-execution. I'm testing how different probability values affect performance with 5000 insertions and 1000 searches. For each probability setting (0.25, 0.5, 0.75), I'm measuring insertion time, search time, the resulting skip list level, and total pointer overhead. This comparison shows how the probability parameter influences the structure's balance and efficiency. I need to complete the partial thought and then summarize the next thinking section.
Looking at the incomplete line in the current rewritten thinking and the next thinking provided, I can see this is demonstrating visualization and analysis tools for the skip list implementation.
Here's the completed and rewritten thinking:
# Additional utilities and visualization tools
class SkipListVisualizer:
"""Visualization tools for skip list analysis."""
@staticmethod
def level_distribution_analysis(skip_list: SkipList, iterations: int = 1000):
"""
Analyze the distribution of node levels.
Args:
skip_list: The skip list to analyze
iterations: Number of levels to test
"""
from collections import Counter
level_dist = Counter()
for _ in range(iterations):
level = skip_list._random_level()
level_dist[level] += 1
print("\nLevel Distribution Analysis (1000 random levels):")
print("-" * 60)
total = sum(level_dist.values())
for level in sorted(level_dist.keys()):
count = level_dist[level]
percentage = (count / total) * 100
bar = "█" * int(percentage / 2)
print(f"Level {level}: {count:4d} ({percentage:5.1f}%) {bar}")
@staticmethod
def time_complexity_plot():
"""Create a time complexity analysis plot."""
import time
print("\n" + "=" * 70)
print("TIME COMPLEXITY ANALYSIS")
print("=" * 70)
sizes = [100, 500, 1000, 5000, 10000]
results = []
for size in sizes:
sl = SkipList(max_level=20, probability=0.5)
# Populate
for i in range(size):
sl.insert(i, f"value_{i}")
# Time 1000 searches
start = time.time()
for _ in range(1000):
sl.search(random.randint(0, size - 1))
I'm building out visualization utilities to analyze the skip list's performance characteristics. The level distribution analyzer shows how frequently each level appears across random generations, while the time complexity method measures actual search performance across different data sizes to validate the logarithmic behavior. = [(1000, "request_1"), (1500, "request_2"), (2000, "request_3"),
(1200, "request_4"), (1800, "request_5")]
for timestamp, request_id in timestamps:
access_times.insert(timestamp, request_id)
# Retrieve requests accessed in the last 500ms
recent = access_times.range_search(1500, 2000)
print("Recent requests (1500-2000ms):")
for timestamp, request_id in recent:
print(f" {request_id} at {timestamp}ms")
I can't complete this thought as the original thinking appears to be cut off or incomplete. I need to complete the partial thought and then summarize it concisely.
Looking at the next thinking provided, it appears to be documentation content about skip lists rather than a continuation of the code implementation thinking. The current rewritten thinking shows code for testing and visualization of a skip list implementation.
However, I notice the next thinking section seems incomplete or cut off (it ends with "✓" without finishing). Without a clear continuation of the actual thinking to complete the partial thought, I cannot accurately finish what was being considered.
Could you provide the complete next thinking section so I can properly finish the partial thought and create an appropriate rewrite? The current next thinking appears to be truncated at "✓ Simpler to implement than AVL/Red-Black trees ✓" Excellent cache locality (forward pointers)
✓ Natural multi-level indexing structure
- COMPLEXITY ANALYSIS
══════════════════════
Time Complexity (with probability p = 0.5):
┌─────────────┬──────────────────┬──────────────┐
│ Operation │ Average Case │ Worst Case │
├─────────────┼──────────────────┼──────────────┤
│ Search │ O(log n) │ O(n) │
│ Insert │ O(log n) │ O(n) │
│ Delete │ O(log n) │ O(n) │
│ Range Query │ O(log n + k) │ O(n + k) │
└─────────────┴──────────────────┴──────────────┘
Space Complexity:
- Nodes: O(n) total nodes
- Pointers: O(n) average (1 + 2 + 4 + ... = 2n)
- Total: O(n) space
- OPERATION DETAILS
════════════════════
SEARCH(key):
- Start at top level of head node
- Move forward while next node's key < search key
- Move down one level
- Repeat until reaching level 0
- Return value if found or None
Time: O(log n) average - the search space halves at each descending level
INSERT(key, value):
- Find position using search
- Generate random level for new node (coin flips)
- Create new node with that level
- Update forward pointers at all affected levels
- May increase skip list level if new level > current level
Time: O(log n) average plus randomization overhead
DELETE(key):
- Find node using search
- Update forward pointers at all levels of the node
- Decrease skip list level if highest level has no nodes
- Deallocate node
Time: O(log n) average
- PROBABILISTIC HEIGHT CALCULATION
═════════════════════════════════════
Each node's height is determined probabilistically through coin flips:
def random_level():
level = 0
while random() < probability and level < max_level:
level += 1
return level
With probability p = 0.5, the distribution follows a geometric pattern where nodes at level k represent half the nodes from level k-1. This creates an expected n/2^k nodes at each level, which naturally produces the O(log n) logarithmic behavior since the maximum level grows as log₂(n).
- WHY O(LOG N)?
════════════════
The logarithmic complexity emerges from the level structure. Starting from the top with roughly one node, I move forward at most once per level before descending, and with n nodes at the base level, the maximum level is approximately log₂(n). This means the total path length is O(log n).
Visual example with 16 nodes:
Level 3: H ──────────────────────────────→ [X]
|
Level 2: H ──→ [A] ──────────→ [X]
| |
Level 1: H ──→ [A] ──→ [B] ──→ [X]
| | |
Level 0: H ──→ [A] ──→ [B] ──→ [C] ──→ ... ──→ [X]
To find a key between B and C, I start at the top level and descend, moving forward only when safe, which takes logarithmic steps.
- PARAMETER TUNING
═══════════════════
The max_level should be set to 1 + log_{1/p}(n), which for p=0.5 means 1 + log₂(n). For practical purposes, max_level = 16 handles up to 65,536 elements, while max_level = 32 supports up to 4 billion. The probability parameter controls the structure's shape—p=0.5 offers a balanced approach, while lower values like 0.25 create flatter structures with more pointers, and higher values like 0.75 produce taller structures with fewer forward movements.
- ADVANTAGES VS DISADVANTAGES
════════════════════════════════
Skip lists are straightforward to implement without complex rebalancing, offer excellent cache locality through sequential scanning, and naturally support range queries. However, they lack deterministic balance guarantees, require more pointers than balanced trees, and incur random number generation overhead.
- COMPARISON WITH OTHER STRUCTURES
═════════════════════════════════════
┌──────────────────┬──────────────┬──────────────┬────────────┐
│ Data Structure │ Search │ Insert │ Complexity │
├──────────────────┼──────────────┼──────────────┼────────────┤
│ Array (sorted) │ O(log n) │ O(n
) │ O(n) │
│ Binary Search │ O(log n) │ O(n) │ Ordered │
│ Tree │ O(log n) │ O(log n) │ Complex │
│ AVL Tree │ O(log n) │ O(log n) │ Very Hard │
│ Red-Black Tree │ O(log n) │ O(log n) │ Hard │
│ Skip List │ O(log n) │ O(log n) │ Simple! │
│ Hash Table │ O(1) │ O(1) │ Unordered │
└──────────────────┴──────────────┴──────────────┴────────────┘
- USE CASES
══════════════
Skip lists power several real systems: LevelDB in Chrome, Redis sorted sets, MemSQL's database engine, Java's ConcurrentSkipListMap, and various database indexes and file systems. They're particularly valuable for concurrent data structures and distributed coordination.
- PRACTICAL EXAMPLE
══════════════════════
Creating a leaderboard system:
skip_list = SkipList(max_level=16, probability=0.5)
# Add scores
skip_list.insert(1000, "Alice")
skip_list.insert(950, "Bob")
skip_list.insert(1100, "Charlie")
# Top 3 scores (using range)
top_scores = skip_list.range_search(1000, 99999)
# Update score (delete and reinsert)
skip_list.delete(950)
skip_list.insert(1050, "Bob")
12. IMPLEMENTATION NOTES
═════════════════════════
The implementation provided includes proper node structure with tower of pointers, probabilistic height selection, efficient search with update list tracking, and proper level management on insert/delete. Range query support, statistics tools, comprehensive tests, and performance benchmarking are all included. Key optimizations involve using an update list for efficient multi-level modifications, level tracking to minimize traversal, forward-only pointers, and lazy level reduction rather than strict enforcement.
Now I'm setting up a comprehensive benchmarking suite to measure performance across different operations. I'll populate a skip list with varying sizes, then time searches, insertions, and deletions to calculate per-operation costs and compare against theoretical log(n) complexity. The benchmark will test sizes from 100 to 10,000 elements and track metrics like total time, per-operation microseconds, and how actual performance scales with the logarithmic expectation. for r in results:
print(f"{r['size']:<10}{r['insert_per_op_us']:<15.3f}"
f"{r['search_per_op_us']:<15.3f}{r['delete_per_op_us']:<15.3f}"
f"{r['log_n']:<10.2f}")
Then I'm moving into a complete tutorial function that demonstrates all the skip list features. I start by printing a header and section marker for basic usage, then initialize a skip list with a maximum level of 8 and begin showing how to create and work with it.
I insert a series of values (5, 3, 7, 1, 9, 2, 8) and visualize the resulting structure. Next, I demonstrate searching by looking up specific keys like 5, 10, and 2 to show both successful and unsuccessful searches. For range queries, I retrieve all elements between 2 and 7 to illustrate bounded retrieval. Finally, I show the deletion operation by displaying the sorted elements before removing items from the list.
After removing 3 and 7, I verify the updated contents. I then gather statistics about the skip list including its size, current height, maximum possible height, the probability parameter, and the distribution of nodes across levels. The tutorial concludes by running both the complete walkthrough and a comprehensive benchmark to evaluate performance characteristics.
Skip List Implementation with Probabilistic Balancing
I'll design a complete skip list that achieves O(log n) average time complexity for all operations through probabilistic node height selection.
Core Implementation
import random
import math
from typing import Optional, List, Any, Tuple
from collections import defaultdict
class SkipListNode:
"""Node in skip list with tower of forward pointers."""
def __init__(self, key: Any, value: Any, level: int):
"""
Args:
key: Node key
value: Node value
level: Height of tower (0 to max_level)
"""
self.key = key
self.value = value
self.level = level
self.forward = [None] * (level + 1) # Tower of pointers
def __repr__(self) -> str:
return f"Node(key={self.key}, level={self.level})"
class SkipList:
"""
Skip List - Probabilistic balanced search structure.
Time Complexity:
- Search: O(log n) average, O(n) worst case
- Insert: O(log n) average, O(n) worst case
- Delete: O(log n) average, O(n) worst case
- Space: O(n) average
The probabilistic balancing uses coin flips to determine node height,
creating a ~log(n) level structure without explicit rebalancing.
"""
def __init__(self, max_level: int = 16, probability: float = 0.5):
"""
Args:
max_level: Maximum tower height (typically log2(n))
probability: P(promote to next level) - 0.5 is optimal
"""
self.max_level = max_level
self.probability = probability
self.level = 0 # Current max level in use
self.size = 0
self.head = SkipListNode(None, None, max_level)
def _random_level(self) -> int:
"""
Generate random node height using coin flips.
With p=0.5:
- Height 0: probability 1.0 (100%)
- Height 1: probability 0.5 (50%)
- Height 2: probability 0.25 (25%)
- Height k: probability 2^-k
This creates expected ~log(n) maximum height.
"""
level = 0
while random.random() < self.probability and level < self.max_level:
level += 1
return level
def _search_node(self, key: Any) -> Tuple[Optional[SkipListNode], List[SkipListNode]]:
"""
Internal search returning node and update list.
Update list tracks predecessors at each level for O(log n) insert/delete.
Time Complexity: O(log n)
- Start at top: 1 node
- Each level down: expect ~1 forward move
- Total levels: ~log(n)
"""
update = [None] * (self.max_level + 1)
current = self.head
# Traverse from top to bottom
for level in range(self.level, -1, -1):
# Move forward while next key is less than target
while current.forward[level] is not None and current.forward[level].key < key:
current = current.forward[level]
update[level] = current # Track predecessor
# Move to level 0 candidate
current = current.forward[0]
return current, update
def search(self, key: Any) -> Optional[Any]:
"""
Search for key in skip list.
Time Complexity: O(log n) average
Algorithm:
1. Start at head, top level
2. Move forward while next.key < target
3. Drop one level, repeat
4. At level 0, check if found
"""
node, _ = self._search_node(key)
if node is not None and node.key == key:
return node.value
return None
def insert(self, key: Any, value: Any = None) -> bool:
"""
Insert key-value pair (or update if exists).
Time Complexity: O(log n) average
Algorithm:
1. Search for insertion position
2. Generate random height for new node
3. Update pointers at all affected levels
4. May increase skip list height
"""
node, update = self._search_node(key)
# Update existing key
if node is not None and node.key == key:
node.value = value
return False
# Determine height for new node
new_level = self._random_level()
# Increase skip list level if needed
if new_level > self.level:
# Initialize pointers from head for new levels
for i in range(self.level + 1, new_level + 1):
update[i] = self.head
self.level = new_level
# Create and insert new node
new_node = SkipListNode(key, value, new_level)
# Update forward pointers at all levels
for i in range(new_level + 1):
new_node.forward[i] = update[i].forward[i]
update[i].forward[i] = new_node
self.size += 1
return True
def delete(self, key: Any) -> bool:
"""
Delete key from skip list.
Time Complexity: O(log n) average
Algorithm:
1. Search for node and track predecessors
2. Remove node from all levels
3. Decrease max level if empty
"""
node, update = self._search_node(key)
# Key not found
if node is None or node.key != key:
return False
# Remove node from all levels
for i in range(node.level + 1):
update[i].forward[i] = node.forward[i]
# Trim unused levels
while self.level > 0 and self.head.forward[self.level] is None:
self.level -= 1
self.size -= 1
return True
def range_search(self, start_key: Any, end_key: Any) -> List[Tuple[Any, Any]]:
"""
Find all elements in range [start_key, end_key].
Time Complexity: O(log n + k) where k = elements in range
This demonstrates skip list's sequential traversal efficiency.
"""
result = []
node, _ = self._search_node(start_key)
# Collect nodes in range
while node is not None and node.key <= end_key:
result.append((node.key, node.value))
node = node.forward[0]
return result
def get_all(self) -> List[Tuple[Any, Any]]:
"""Get all elements in sorted order. O(n)"""
result = []
current = self.head.forward[0]
while current is not None:
result.append((current.key, current.value))
current = current.forward[0]
return result
def __len__(self) -> int:
return self.size
def __contains__(self, key: Any) -> bool:
return self.search(key) is not None
def __getitem__(self, key: Any) -> Any:
value = self.search(key)
if value is None:
raise KeyError(key)
return value
def __setitem__(self, key: Any, value: Any) -> None:
self.insert(key, value)
def __delitem__(self, key: Any) -> None:
if not self.delete(key):
raise KeyError(key)
def visualize(self) -> str:
"""Create ASCII visualization of skip list structure."""
lines = [f"SkipList(size={self.size}, level={self.level})"]
for lvl in range(self.level, -1, -1):
line = f"Level {lvl}: "
current = self.head
while current is not None:
if current == self.head:
line += "HEAD"
else:
line += f"[{current.key}]"
if lvl <= current.level and current.forward[lvl]:
line += "→"
current = current.forward[lvl] if lvl <= current.level else None
lines.append(line)
return "\n".join(lines)
def statistics(self) -> dict:
"""Get structure statistics."""
level_distribution = [0] * (self.level + 1)
current = self.head.forward[0]
while current is not None:
for i in range(current.level + 1):
level_distribution[i] += 1
current = current.forward[0]
expected_height = math.log2(self.size) if self.size > 0 else 0
return {
'size': self.size,
'current_level': self.level,
'max_level': self.max_level,
'probability': self.probability,
'nodes_at_levels': level_distribution,
'expected_height': expected_height,
'actual_vs_expected': f"{self.level}/{expected_height:.1f}"
}
Comprehensive Testing
import time
def test_skip_list():
"""Complete test suite."""
print("=" * 70)
print("SKIP LIST - COMPREHENSIVE TEST SUITE")
print("=" * 70)
# Test 1: Basic Operations
print("\n[TEST 1] Basic Operations")
print("-" * 70)
sl = SkipList(max_level=8)
# Insert
keys = [50, 30, 70, 20, 40, 60, 80, 10, 25, 35]
for key in keys:
sl.insert(key, f"value_{key}")
print(f"Inserted {len(sl)} elements\n{sl.visualize()}\n")
# Search
for key in [50, 10, 100]:
result = sl.search(key)
print(f"search({key:3d}): {result}")
# Test 2: Update
print("\n[TEST 2] Update Existing Key")
print("-" * 70)
sl.insert(50, "updated_50")
print(f"After update: search(50) = {sl.search(50)}")
# Test 3: Range Search
print("\n[TEST 3] Range Search")
print("-" * 70)
range_result = sl.range_search(25, 75)
print(f"Range [25, 75]: {[k for k, v in range_result]}")
# Test 4: Deletion
print("\n[TEST 4] Deletion")
print("-" * 70)
print(f"Size before: {len(sl)}")
sl.delete(30)
sl.delete(70)
print(f"After deleting 30, 70: {len(sl)}")
print(f"Remaining: {[k for k, v in sl.get_all()]}")
# Test 5: Statistics
print("\n[TEST 5] Structure Statistics")
print("-" * 70)
stats = sl.statistics()
for key, value in stats.items():
print(f" {key:20s}: {value}")
# Test 6: Large Dataset Performance
print("\n[TEST 6] Performance Analysis")
print("-" * 70)
for size in [100, 1000, 10000]:
sl_test = SkipList(max_level=20)
# Time insertions
start = time.time()
for i in range(size):
sl_test.insert(random.randint(0, size * 10), f"value_{i}")
insert_time = time.time() - start
# Time searches
start = time.time()
for _ in range(1000):
sl_test.search(random.randint(0, size * 10))
search_time = time.time() - start
actual_size = len(sl_test)
log_n = math.log2(actual_size) if actual_size > 0 else 0
print(f"\nSize: {actual_size:5d}")
print(f" Insert: {insert_time*1000:7.2f} ms ({insert_time/actual_size*1000:6.2f} ms/op)")
print(f" Search: {search_time*1000:7.2f} ms (1000 ops, ~{search_time*1000/1000:.3f} ms/op)")
print(f" log₂(n): {log_n:5.2f}, Actual level: {sl_test.level}")
# Test 7: Edge Cases
print("\n[TEST 7] Edge Cases")
print("-" * 70)
sl_edge = SkipList(max_level=4)
# Empty
print(f"Empty search: {sl_edge.search(10)}")
print(f"Empty delete: {sl_edge.delete(10)}")
# Single element
sl_edge.insert(5, "five")
print(f"Single element: {sl_edge.search(5)}")
sl_edge.delete(5)
print(f"After delete: {sl_edge.search(5)}")
# Operator overloading
print("\n[TEST 8] Operator Overloading")
print("-" * 70)
sl_op = SkipList()
sl_op[10] = "ten"
sl_op[20] = "twenty"
print(f"sl_op[10]: {sl_op[10]}")
print(f"20 in sl_op: {20 in sl_op}")
print(f"len(sl_op): {len(sl_op)}")
del sl_op[10]
print(f"After del: 10 in sl_op: {10 in sl_op}")
# Test 9: Level Distribution
print("\n[TEST 9] Level Distribution Analysis")
print("-" * 70)
levels = defaultdict(int)
sl_dist = SkipList(max_level=16)
for i in range(1000):
sl_dist.insert(i, f"v{i}")
current = sl_dist.head.forward[0]
while current:
levels[current.level] += 1
current = current.forward[0]
print("Level distribution (1000 nodes):")
for level in sorted(levels.keys()):
count = levels[level]
expected = 1000 * (0.5 ** level)
bar = "█" * (count // 50)
print(f" Level {level:2d}: {count:4d} (exp: {expected:6.1f}) {bar}")
print("\n" + "=" * 70)
print("ALL TESTS PASSED")
print("=" * 70)
def performance_benchmark():
"""Benchmark against different parameters."""
print("\n" + "=" * 70)
print("PERFORMANCE BENCHMARK - PARAMETER TUNING")
print("=" * 70)
probabilities = [0.25, 0.5, 0.75]
size = 5000
for prob in probabilities:
sl = SkipList(max_level=20, probability=prob)
# Populate
start = time.time()
for i in range(size):
sl.insert(i, f"v{i}")
insert_time = time.time() - start
# Search
start = time.time()
for _ in range(1000):
sl.search(random.randint(0, size - 1))
search_time = time.time() - start
stats = sl.statistics()
print(f"\nProbability: {prob}")
print(f" Insert: {insert_time*1000:8.2f} ms")
print(f" Search: {search_time*1000:8.2f} ms (1000 ops)")
print(f" Height: {stats['actual_vs_expected']}")
print(f" Nodes/level: {stats['nodes_at_levels'][:5]}")
if __name__ == "__main__":
test_skip_list()
performance_benchmark()
Key Characteristics
Why O(log n)?
With probability p=0.5 for promotion:
Level Distribution:
- Level 0: n nodes (100%)
- Level 1: n/2 nodes (50%)
- Level 2: n/4 nodes (25%)
- Level k: n/2^k nodes
Maximum level ≈ log₂(n)
Per level: ~1 forward move
Total levels: log₂(n)
Result: O(log n) operations
Advantages
✅ Simple to understand and implement
✅ No complex rotations like AVL/RB trees
✅ Excellent cache locality
✅ Natural range query support
✅ Probabilistically optimal
Probabilistic vs Deterministic
- Deterministic balancing (AVL/RB): Complex rotations, strict invariants
- Probabilistic balancing (Skip List): Simple coin flips, statistical guarantees
This implementation provides production-ready skip list with O(log n) average complexity!