TRT
Sign in
hardExpertLeetCode#skip list#probabilistic balance#forward pointers

Design a skip list

Implement search, add and erase on a skip list with probabilistic heights, handle duplicates correctly, and measure how close average searches stay to log2 n.

The Runtime Theory Team1 min read
Taught inSkip listsPro — members onlyA skip list keeps keys in one sorted list and gives each node extra forward lanes picked by coin flips at insert time. Search starts on the top lane and drops a lane whenever it runs out of room, giving O(log n) expected time with no rotations; deleting unlinks the node and stops.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inadd 1, 2, 3; search 0; add 4; search 1; erase 0; erase 1; search 1

outfalse, true, false, true, false

inadd 7 twice; then search, erase, search, erase, search, erase

outtrue, true, true, true, false, false

in100,000 sorted inserts, then average forward steps per search

outabout 16 steps, near log2(100,000) = 16.6

inerase a value that was never added

outfalse, with no pointer changed

Implement LeetCode 1206's Skiplist class: search(target) reports whether the value exists, add(num) inserts it — duplicates allowed — and erase(num) removes one instance and reports whether it found one. All three average O(log n), and no built-in collections beyond linked nodes are allowed. Heights come from a fair coin per level: a node starts at height 1 and grows one level for each head, capped at 16.

Before you code

Settle two decisions first: how a height is sampled (and what caps it), and how the walk records the predecessor of the new or removed node on every lane it touches. Both add and erase need that predecessor array, so one top-down walk should serve all three operations.

Hints

  1. Walk with strict < comparisons; equal keys end up adjacent, which is what lets duplicates coexist and lets erase remove exactly one of them.
  2. Splice like the lesson's insert: record update[lvl] while walking, then write two pointers per lane the node owns.
  3. For erase, walk the same way, check the node after the stopping point for equality, unlink it from every lane it occupies, and shrink the top lane count while the head's highest lane is empty.
  4. Measure your result: run 100,000 sorted inserts, then search for existing and missing keys while counting forward steps. The average lands near 16, against log2(100,000) = 16.6 — the geometric thinning the lesson describes.

What it practices

Probabilistic balance without rotations, from Skip lists.

Not started

Sign in to save your learning progress.

Sign in to save