Design Skiplist
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)returnstrueiftargetis currently stored, andfalseotherwise.add(num)insertsnum. The same value may be added more than once; every copy is kept.erase(num)removes one copy ofnumand returnstrue. Ifnumis not stored, it changes nothing and returnsfalse.
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^4calls in total tosearch,addanderase.
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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| Sorted array list with binary search | O(log n) search, O(n) add and erase | O(n) |
| Optimal (skiplist with random tower heights) | O(log n) expected per operation | O(n) expected |
1Sorted array list with binary search
O(log n) search, O(n) add and eraseBinary search takes O(log n) steps; an insert or remove in the middle of an array moves up to n elements.O(n)One array slot per stored value.Ignore the linked structure and keep every value, duplicates included, in a sorted array list. A binary search for the first position whose value is at least x answers everything: search checks whether that position holds the target, add inserts the number there (which keeps the list sorted), and erase removes the element there if it equals the number. Searching costs O(log n), but inserting or removing in the middle of an array shifts every later element, so add and erase are O(n).
lowerBound(x): binary search for the first index whose value is>= x.search(t):i = lowerBound(t); return whetheriis inside the list andvals[i] == t.add(x): insertxatlowerBound(x).erase(x):i = lowerBound(x); ifvals[i] != x(oriis past the end) return false; otherwise remove indexiand return true.
class Skiplist {
private final List<Integer> vals = new ArrayList<>();
public Skiplist() {
}
private int lowerBound(int x) {
int lo = 0, hi = vals.size();
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (vals.get(mid) < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
public boolean search(int target) {
int i = lowerBound(target);
return i < vals.size() && vals.get(i) == target;
}
public void add(int num) {
vals.add(lowerBound(num), num);
}
public boolean erase(int num) {
int i = lowerBound(num);
if (i == vals.size() || vals.get(i) != num) return false;
vals.remove(i);
return true;
}
}class Skiplist:
def __init__(self):
self.vals = []
def lowerBound(self, x: int) -> int:
lo, hi = 0, len(self.vals)
while lo < hi:
mid = (lo + hi) // 2
if self.vals[mid] < x:
lo = mid + 1
else:
hi = mid
return lo
def search(self, target: int) -> bool:
i = self.lowerBound(target)
return i < len(self.vals) and self.vals[i] == target
def add(self, num: int) -> None:
self.vals.insert(self.lowerBound(num), num)
def erase(self, num: int) -> bool:
i = self.lowerBound(num)
if i == len(self.vals) or self.vals[i] != num:
return False
self.vals.pop(i)
return Trueclass Skiplist {
vector<int> vals;
int lowerBound(int x) {
int lo = 0, hi = vals.size();
while (lo < hi) {
int mid = (lo + hi) / 2;
if (vals[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
public:
Skiplist() {
}
bool search(int target) {
int i = lowerBound(target);
return i < (int) vals.size() && vals[i] == target;
}
void add(int num) {
vals.insert(vals.begin() + lowerBound(num), num);
}
bool erase(int num) {
int i = lowerBound(num);
if (i == (int) vals.size() || vals[i] != num) return false;
vals.erase(vals.begin() + i);
return true;
}
};class Skiplist {
constructor() {
this.vals = [];
}
lowerBound(x) {
let lo = 0, hi = this.vals.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (this.vals[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
search(target) {
const i = this.lowerBound(target);
return i < this.vals.length && this.vals[i] === target;
}
add(num) {
this.vals.splice(this.lowerBound(num), 0, num);
}
erase(num) {
const i = this.lowerBound(num);
if (i === this.vals.length || this.vals[i] !== num) return false;
this.vals.splice(i, 1);
return true;
}
}2Optimal (skiplist with random tower heights)
O(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.O(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.
- Keep a head node with
MAX_LEVEL = 16next pointers andlevel, the number of levels currently in use. search(t): from the top level down, advance whilenext.val < t; then return whether the level-0 successor exists and equalst.add(x): walk down the same way, saving the predecessor on each level inupdate; draw a random heightlv; levels above the oldlevelgetheadas predecessor; link the new node afterupdate[i]for everyi < lv.erase(x): walk down saving predecessors; lettargetbe the level-0 successor; if it is missing or notx, return false. Otherwise setupdate[i].next[i] = target.next[i]for each level of its tower, shrinklevelwhile 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;
}
}import random
class Node:
def __init__(self, val: int, height: int):
self.val = val
self.next = [None] * height
class Skiplist:
MAX_LEVEL = 16
def __init__(self):
self.head = Node(-1, self.MAX_LEVEL)
self.rng = random.Random(7)
self.level = 1
def randomLevel(self) -> int:
lv = 1
while lv < self.MAX_LEVEL and self.rng.random() < 0.5:
lv += 1
return lv
def search(self, target: int) -> bool:
cur = self.head
for i in range(self.level - 1, -1, -1):
while cur.next[i] is not None and cur.next[i].val < target:
cur = cur.next[i]
cur = cur.next[0]
return cur is not None and cur.val == target
def add(self, num: int) -> None:
update = [None] * self.MAX_LEVEL
cur = self.head
for i in range(self.level - 1, -1, -1):
while cur.next[i] is not None and cur.next[i].val < num:
cur = cur.next[i]
update[i] = cur
lv = self.randomLevel()
for i in range(self.level, lv):
update[i] = self.head
self.level = max(self.level, lv)
node = Node(num, lv)
for i in range(lv):
node.next[i] = update[i].next[i]
update[i].next[i] = node
def erase(self, num: int) -> bool:
update = [None] * self.MAX_LEVEL
cur = self.head
for i in range(self.level - 1, -1, -1):
while cur.next[i] is not None and cur.next[i].val < num:
cur = cur.next[i]
update[i] = cur
target = cur.next[0]
if target is None or target.val != num:
return False
for i in range(len(target.next)):
update[i].next[i] = target.next[i]
while self.level > 1 and self.head.next[self.level - 1] is None:
self.level -= 1
return Trueclass Skiplist {
static const int MAX_LEVEL = 16;
struct Node {
int val;
vector<Node*> next;
Node(int v, int height) : val(v), next(height, nullptr) {}
};
Node* head = new Node(-1, MAX_LEVEL);
mt19937 rng{7};
int level = 1;
int randomLevel() {
int lv = 1;
while (lv < MAX_LEVEL && (rng() & 1)) lv++;
return lv;
}
public:
Skiplist() {
}
bool search(int target) {
Node* cur = head;
for (int i = level - 1; i >= 0; i--) {
while (cur->next[i] && cur->next[i]->val < target) cur = cur->next[i];
}
cur = cur->next[0];
return cur && cur->val == target;
}
void add(int num) {
vector<Node*> update(MAX_LEVEL, nullptr);
Node* cur = head;
for (int i = level - 1; i >= 0; i--) {
while (cur->next[i] && 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 = 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;
}
}
bool erase(int num) {
vector<Node*> update(MAX_LEVEL, nullptr);
Node* cur = head;
for (int i = level - 1; i >= 0; i--) {
while (cur->next[i] && cur->next[i]->val < num) cur = cur->next[i];
update[i] = cur;
}
Node* target = cur->next[0];
if (!target || target->val != num) return false;
for (int i = 0; i < (int) target->next.size(); i++) {
update[i]->next[i] = target->next[i];
}
delete target;
while (level > 1 && !head->next[level - 1]) level--;
return true;
}
};class SkipNode {
constructor(val, height) {
this.val = val;
this.next = new Array(height).fill(null);
}
}
class Skiplist {
constructor() {
this.MAX_LEVEL = 16;
this.head = new SkipNode(-1, this.MAX_LEVEL);
this.seed = 7;
this.level = 1;
}
coin() {
// a small deterministic generator; any fair coin works
this.seed = (this.seed * 48271) % 2147483647;
return this.seed < 1073741824;
}
randomLevel() {
let lv = 1;
while (lv < this.MAX_LEVEL && this.coin()) lv++;
return lv;
}
search(target) {
let cur = this.head;
for (let i = this.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;
}
add(num) {
const update = new Array(this.MAX_LEVEL).fill(null);
let cur = this.head;
for (let i = this.level - 1; i >= 0; i--) {
while (cur.next[i] !== null && cur.next[i].val < num) cur = cur.next[i];
update[i] = cur;
}
const lv = this.randomLevel();
for (let i = this.level; i < lv; i++) update[i] = this.head;
this.level = Math.max(this.level, lv);
const node = new SkipNode(num, lv);
for (let i = 0; i < lv; i++) {
node.next[i] = update[i].next[i];
update[i].next[i] = node;
}
}
erase(num) {
const update = new Array(this.MAX_LEVEL).fill(null);
let cur = this.head;
for (let i = this.level - 1; i >= 0; i--) {
while (cur.next[i] !== null && cur.next[i].val < num) cur = cur.next[i];
update[i] = cur;
}
const target = cur.next[0];
if (target === null || target.val !== num) return false;
for (let i = 0; i < target.next.length; i++) {
update[i].next[i] = target.next[i];
}
while (this.level > 1 && this.head.next[this.level - 1] === null) this.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.