- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 67 lines of Python from the credited upstream file 1206.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from dataclasses import dataclass2 3 4@dataclass5class Node:6 val: int = -17 next: 'Node' = None8 down: 'Node' = None9 10 11class Skiplist:12 def __init__(self):13 self.dummy = Node()14 15 def search(self, target: int) -> bool:16 node = self.dummy17 while node:18 while node.next and node.next.val < target:19 node = node.next20 if node.next and node.next.val == target:21 return True22 23 node = node.down24 return False25 26 def add(self, num: int) -> None:27 28 nodes = []29 node = self.dummy30 while node:31 while node.next and node.next.val < num:32 node = node.next33 nodes.append(node)34 35 node = node.down36 37 shouldInsert = True38 down = None39 while shouldInsert and nodes:40 node = nodes.pop()41 node.next = Node(num, node.next, down)42 down = node.next43 shouldInsert = random.getrandbits(1) == 044 45 46 if shouldInsert:47 self.dummy = Node(-1, None, self.dummy)48 49 def erase(self, num: int) -> bool:50 node = self.dummy51 found = False52 while node:53 while node.next and node.next.val < num:54 node = node.next55 if node.next and node.next.val == num:56 57 node.next = node.next.next58 found = True59 60 node = node.down61 return found62 63 64 def _advance(self, node: Node, target: int) -> None:65 while node.next and node.next.val < target:66 node = node.next67