Design Skiplist

Hard Design Data Structures Randomized Algorithms

Design Skiplist is a hard design data structures problem solved with the randomized algorithms pattern. The best approach, optimal (skiplist with random tower heights), runs in O(log n) expected per operation time and O(n) expected space. Below are 2 approaches in Java, Python, C++ and JavaScript, from sorted array list with binary search up.

Problem

Build a skiplist from scratch, without using any library container that keeps values sorted for you. A skiplist stores a sorted collection of numbers in a stack of linked lists: the bottom list holds every value in order, and each list above it holds only some of the values below, so a search can skip far ahead on the upper lists and then drop down to finish. With random choices for which values reach the upper lists, search, add and erase each take O(log n) time on average.

Implement the class Skiplist:

  • Skiplist() creates an empty skiplist.
  • search(target) returns true if target is currently stored, and false otherwise.
  • add(num) inserts num. The same value may be added more than once; every copy is kept.
  • erase(num) removes one copy of num and returns true. If num is not stored, it changes nothing and returns false.

Any random choices your implementation makes must not change the results: the answers depend only on the sequence of calls.

Examples

Example 1

Input
Skiplist(), add(5), add(2), add(9), search(4), add(4), search(4), erase(7), erase(2), search(2)
Output
false, true, false, true, false
Why
After adding 5, 2 and 9 the list holds 2, 5, 9, so 4 is not found. Once 4 is added, search(4) is true. 7 was never added, so erasing it returns false. Erasing 2 succeeds, and after that 2 can no longer be found.

Example 2

Input
Skiplist(), add(3), add(3), erase(3), search(3), erase(3), search(3), erase(3)
Output
true, true, true, false, false
Why
3 is added twice. The first erase removes one copy, so search(3) still finds the other. The second erase removes the last copy; after that search(3) is false and a third erase has nothing to remove.

Constraints

  • 0 <= num, target <= 2 * 10^4
  • At most 5 * 10^4 calls in total to search, add and erase.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (2 examples, or your own). Submit also runs 16 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Sorted array list with binary searchO(log n) search, O(n) add and eraseO(n)
Optimal (skiplist with random tower heights)O(log n) expected per operationO(n) expected

2Optimal (skiplist with random tower heights)

TimeO(log n) expected per operationWith coin-flip heights there are about log n levels, and the expected number of steps to the right on each level is a small constant, so each walk from the top down takes O(log n) expected steps.
SpaceO(n) expectedA tower has 2 levels on average (1 + 1/2 + 1/4 + ...), so the total number of next pointers is about 2n.

Build a sorted linked list with several levels. Level 0 links every node in order. Each node is a tower of some height, and on level i it links to the next node whose tower is at least i + 1 tall, so higher levels are sparser express lanes. A sentinel head node has the full height. To find a value, start at the head on the highest level in use; move right while the next node's value is smaller than the target, and when it is not, drop one level. At level 0 the next node is the first one that is at least the target. add records, on every level, the last node visited before dropping down (the update array): those are the predecessors. It then picks a height by flipping coins (each extra level with probability one half, capped at 16) and splices the new tower in after those predecessors, level by level. erase finds the predecessors the same way, checks that the next node on level 0 holds the number, and unlinks that one node on each level of its tower. Duplicates are ordinary nodes next to each other. The random heights only affect speed: the level-0 list is always the sorted multiset, so every answer is the same whatever the coins say.

  1. Keep a head node with MAX_LEVEL = 16 next pointers and level, the number of levels currently in use.
  2. search(t): from the top level down, advance while next.val < t; then return whether the level-0 successor exists and equals t.
  3. add(x): walk down the same way, saving the predecessor on each level in update; draw a random height lv; levels above the old level get head as predecessor; link the new node after update[i] for every i < lv.
  4. erase(x): walk down saving predecessors; let target be the level-0 successor; if it is missing or not x, return false. Otherwise set update[i].next[i] = target.next[i] for each level of its tower, shrink level while the top level is empty, and return true.
class Skiplist {
    private static final int MAX_LEVEL = 16;

    private static class Node {
        int val;
        Node[] next;

        Node(int val, int height) {
            this.val = val;
            this.next = new Node[height];
        }
    }

    private final Node head = new Node(-1, MAX_LEVEL);
    private final Random rng = new Random(7);
    private int level = 1;

    public Skiplist() {
    }

    private int randomLevel() {
        int lv = 1;
        while (lv < MAX_LEVEL && rng.nextBoolean()) lv++;
        return lv;
    }

    public boolean search(int target) {
        Node cur = head;
        for (int i = level - 1; i >= 0; i--) {
            while (cur.next[i] != null && cur.next[i].val < target) cur = cur.next[i];
        }
        cur = cur.next[0];
        return cur != null && cur.val == target;
    }

    public void add(int num) {
        Node[] update = new Node[MAX_LEVEL];
        Node cur = head;
        for (int i = level - 1; i >= 0; i--) {
            while (cur.next[i] != null && cur.next[i].val < num) cur = cur.next[i];
            update[i] = cur;
        }
        int lv = randomLevel();
        for (int i = level; i < lv; i++) update[i] = head;
        level = Math.max(level, lv);
        Node node = new Node(num, lv);
        for (int i = 0; i < lv; i++) {
            node.next[i] = update[i].next[i];
            update[i].next[i] = node;
        }
    }

    public boolean erase(int num) {
        Node[] update = new Node[MAX_LEVEL];
        Node cur = head;
        for (int i = level - 1; i >= 0; i--) {
            while (cur.next[i] != null && cur.next[i].val < num) cur = cur.next[i];
            update[i] = cur;
        }
        Node target = cur.next[0];
        if (target == null || target.val != num) return false;
        for (int i = 0; i < target.next.length; i++) {
            update[i].next[i] = target.next[i];
        }
        while (level > 1 && head.next[level - 1] == null) level--;
        return true;
    }
}

Edge cases to test

  • erase or search on an empty structure: false
  • Duplicates: add the same value several times, and each erase removes exactly one copy
  • erase of a value that was never added, or was already erased: false, and nothing changes
  • Values at the boundaries 0 and 20000
  • Strictly increasing or decreasing insertions, which would make an unbalanced search tree degenerate
  • The random tower heights must never change an answer, only the speed

Hints

Hint 1

The simplest correct version keeps every value in a sorted array and binary searches it. Searching is fast; what is slow?

Hint 2

A sorted linked list makes inserting cheap once you know where, but finding the spot means walking node by node.

Hint 3

Add express lanes: let some nodes also appear on a higher-level list that skips over many nodes. Search from the top lane down, dropping a level whenever the next node would overshoot.

Hint 4

Choose each new node's height by flipping a coin until it lands tails. About half the nodes reach level 2, a quarter reach level 3, and so on, which gives O(log n) expected work per operation.

Hint 5

For add and erase, remember the last node visited on each level: those are exactly the nodes whose next pointers must change.

FAQ

What is the best time complexity for Design Skiplist?

Optimal (skiplist with random tower heights) runs in O(log n) expected per operation time and O(n) expected extra space. With coin-flip heights there are about log n levels, and the expected number of steps to the right on each level is a small constant, so each walk from the top down takes O(log n) expected steps.

Which pattern does Design Skiplist use?

It is a design data structures problem that uses the randomized algorithms pattern. Other problems with the same pattern: Shuffle an Array.

Is there a brute force solution for Design Skiplist?

Yes. Sorted array list with binary search takes O(log n) search, O(n) add and erase time and O(n) space. Ignore the linked structure and keep every value, duplicates included, in a sorted array list.

Which edge cases should I test for Design Skiplist?

erase or search on an empty structure: false; Duplicates: add the same value several times, and each erase removes exactly one copy; erase of a value that was never added, or was already erased: false, and nothing changes; Values at the boundaries 0 and 20000; Strictly increasing or decreasing insertions, which would make an unbalanced search tree degenerate; The random tower heights must never change an answer, only the speed.