- 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
- 64 lines of Java from the credited upstream file 1206.java.
- The implementation visibly relies on work queue.
- 5 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.
1class Node {2 public int val;3 public Node next;4 public Node down;5 public Node(int val, Node next, Node down) {6 this.val = val;7 this.next = next;8 this.down = down;9 }10}11 12class Skiplist {13 public boolean search(int target) {14 for (Node node = dummy; node != null; node = node.down) {15 node = advance(node, target);16 if (node.next != null && node.next.val == target)17 return true;18 }19 return false;20 }21 22 public void add(int num) {23 24 Deque<Node> nodes = new ArrayDeque<>();25 for (Node node = dummy; node != null; node = node.down) {26 node = advance(node, num);27 nodes.push(node);28 }29 30 Node down = null;31 boolean shouldInsert = true;32 while (shouldInsert && !nodes.isEmpty()) {33 Node prev = nodes.poll();34 prev.next = new Node(num, prev.next, down);35 down = prev.next;36 shouldInsert = Math.random() < 0.5;37 }38 39 40 if (shouldInsert)41 dummy = new Node(-1, null, dummy);42 }43 44 public boolean erase(int num) {45 boolean found = false;46 for (Node node = dummy; node != null; node = node.down) {47 node = advance(node, num);48 if (node.next != null && node.next.val == num) {49 node.next = node.next.next;50 found = true;51 }52 }53 return found;54 }55 56 private Node dummy = new Node(-1, null, null);57 58 private Node advance(Node node, int target) {59 while (node.next != null && node.next.val < target)60 node = node.next;61 return node;62 }63}64