Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Probabilistic Structures

The Skip List.

Watch the explainer

A sorted linked list is honest but slow: to find a value you walk every node, O(n). The skip list adds express lanes — sparse extra layers stacked on top — so search rides far up high and drops down to refine. The payoff is O(log n) search, insert and delete, matching a balanced tree, but built from coin flips instead of rotations.

O(log n) expected · probabilistic · no rotations
express lane

A sparse upper layer that skips over many nodes at once.

right then down

Search moves right while it can, drops a level when it would overshoot.

coin-flip levels

Each node’s height is random: ~½ reach level 1, ¼ level 2…

tree rival

Same O(log n) as a balanced tree — far simpler code, easy to make concurrent.

skiplist.js — right while you can, else drop
search for: 19 7 25 12
Ready
A sorted set stored as a skip list — sparse express lanes on top, every value on the bottom. Pick a target and press Step: from the top-left, move right while the next value ≤ target, else drop a level.
3
level
0
hops
–
vs linear

How it works

Picture a highway map. The bottom lane is a local road stopping at every town (every value). Above it are express lanes that skip most towns. To reach a destination you get on the highest express lane, drive right until the next exit would overshoot, drop to a lower lane, and repeat — refining as the lanes get denser. That’s a skip-list search.

1

Start top-left

Begin at the head node on the highest express lane.

2

Go right while you can

While the next node’s value is ≤ your target, move to it. Each hop skips everything between.

3

Overshoot → drop a level

When the next value would exceed the target, drop to the lane below and keep going right.

✓

Land at level 0

At the bottom lane you arrive exactly at the target, or at the gap where it would be. ~log₂(n) hops total.

Search
O(log n) exp.
Insert / delete
O(log n) exp.
Space
O(n) expected
Rotations
none

The code

# search a skip list: right while you can, else drop def search(head, target): node = head for level in reversed(range(head.height)): while node.next[level] and node.next[level].val <= target: node = node.next[level] # skip right return node if node.val == target else None # insert: search for position, then flip a coin for height — # promote to the next level with probability 1/2, splice in.

Insert and delete reuse the same search to find the position, then splice the node into every level it reaches. The height comes from a coin flip loop — no rebalancing logic at all. That simplicity, plus easy concurrency, is why Redis sorted sets and several databases pick skip lists over balanced trees.

Quick check

1. Why do the express lanes make search O(log n)?

2. What’s the big advantage over a balanced tree?

FAQ

What is a skip list?

A sorted linked list with sparse express-lane layers stacked on top, giving O(log n) expected search, insert and delete from linked-list operations plus coin-flip node heights.

How does search work?

From the top-left, move right while the next value ≤ target, drop a level when it would overshoot, and repeat down to the bottom lane — landing on the target or its gap.

Where are skip lists used?

Redis sorted sets, LevelDB/RocksDB memtables, Apache Lucene, and various concurrent maps — anywhere an ordered structure with simple, concurrent-friendly O(log n) ops is wanted.

Are the O(log n) bounds guaranteed?

They're expected, not worst-case — a run of unlucky coin flips could skew the levels. In practice the probability of bad behavior is astronomically small, and the simplicity usually wins over a tree's hard guarantee.

The picture: express lanes over one sorted list

L4 L3 L2 L1 L0 2 5 5 5 5 7 9 12 12 12 12 12 15 15 15 19 22 22 25 28 28 3 hops to reach 19; a plain list takes 7
Ten keys, each with a height drawn by coin flips (Python random.Random(42), promote while random() < 0.5): 1, 4, 1, 1, 5, 3, 1, 2, 1, 2. Level 0 holds every key; level 4 holds only 12. The highlighted boxes are the search for 19: ride level 4 to 12, drop to level 2, hop to 15, drop to level 0, hop to 19. The marked box is 22 on level 1, the node that would overshoot and forces the last drop.

Worked example, step by step

Search for 19 in the list drawn above. At each step look at the next node on the current level: if its key is ≤ 19, move onto it; otherwise (or if the lane ends) drop one level. Start at the head on level 4.

StepLevelAtNext on levelDecision
14head1212 ≤ 19: move right
2412noneend of lane: drop a level
3312noneend of lane: drop a level
42121515 ≤ 19: move right
5215noneend of lane: drop a level
61152222 > 19: drop a level
70151919 ≤ 19: move right
80192222 > 19: stop

Eight look-aheads and three hops found a key that sits seventh in the list. Two things stand out. First, levels 3 and 1 are crossed without a hop: level 3 has nothing after 12, and on level 1 the next key (22) is already too big. A level costs one comparison even when it does no work, which is why the constant in front of log n is more than one. Second, the final drop at step 7 lands on level 0, where the only remaining node, 19, is the target. A search for the absent key 20 takes exactly the same eight steps and ends on 19, the predecessor: a miss costs the same as a hit, and the node it stops on is where an insert would splice. Insertion reuses this walk; it just records the last node visited on each level, since those are the pointers to rewire.

Complexity and trade-offs

CaseTimeSpaceWhy
Skip list, searchO(log n) expectedO(n), about 2 pointers per keyn = 100,000 sequential keys, heights from Random(1): 31.1 comparisons per search on average, 1.998 pointers per key.
Sorted array + binary searchO(log n) worstO(n)15.6 comparisons on the same n, but insert shifts up to n elements.
Sorted linked listO(n)O(n), 1 pointer per key(n + 1) / 2 comparisons on average: 50,000.5 for the same n.
Balanced treeO(log n) worstO(n)Guaranteed bound, at the price of rotation code for insert and delete.
Skip list, worst caseO(n)O(n)Possible if every coin flip fails, but the chance shrinks exponentially in the number of nodes affected.

The skip list does about twice the comparisons of binary search on the same data (31.1 against 15.6) and pays for it in extra pointers, but it supports inserting and deleting in the middle without shifting anything. The bound is expected, not guaranteed, and it varies with the draw: for n = 1000, 200 different seeds produced an average of 16.6 comparisons in the luckiest build and 26.8 in the unluckiest. A balanced tree trades the other way: a hard bound, more complicated code.

Common mistakes

  • Not rejecting duplicates

    Inserting 5, 7, then 7 again, with a descent that stops before the key and no equality check, yields the list [5, 7, 7]. After the walk, look at update[0].next[0]: if its key equals the new key, return without inserting.

  • Forgetting to raise the current level

    If a new node is taller than the list’s current level and you never update that level (or link the head on the new levels), the tall nodes are only linked at level 0. With 1000 keys built that way, the average search cost is 501.5 comparisons; with the level raised correctly it is 26.8. Everything still returns correct answers, so only timing exposes it.

  • Unlinking at level 0 only

    Delete key 15 (height 3) by splicing it out of the bottom lane alone. to_list() then shows [2, 5, 7, 9, 12, 19, 22, 25, 28], yet a search for 15 still returns True, because the descent reaches the stale node on level 2 and never reaches level 0. Delete must unlink the node on every level it occupies.

  • Descending with &lt; and forgetting the last check

    The page’s search moves while next.key ≤ target. If you use < instead, you stop on the predecessor, and returning node.key == target reports False for 19, which is in the list. The fix is one more step: compare node.next[0].key with the target.

  • Expecting a guarantee

    Tests that assert a hop count will be flaky. The same 1000 keys cost between 16.6 and 26.8 comparisons per search across 200 seeds. Assert correctness, and measure averages over many seeds if you must measure cost.

Where this shows up

  • Ordered in-memory maps

    Any ordered key-value store that needs inserts, deletes and range reads in one structure can use one. Level 0 is a sorted list, so a range scan finds the start with an O(log n) descent and then simply walks forward.

  • Concurrent access

    Inserting a node changes a few forward pointers, and each is a single compare-and-swap target. That locality is why lock-free ordered maps are often built from skip lists; Java’s ConcurrentSkipListMap is one. A rotation in a balanced tree touches several nodes at once, which is much harder to make atomic.

  • Write buffers in storage engines

    A database often keeps recent writes in a sorted in-memory structure before flushing to disk. A skip list suits it: inserts are cheap, readers do not block, and the flush is a walk along level 0.

  • Rank queries

    Store, on each pointer, how many level-0 nodes it jumps over. Summing those spans on the way down gives the rank of a key, and descending by span finds the k-th key, both in expected O(log n).

SOLVE IT YOURSELF

Solve it: build a skip list

A balanced tree gets O(log n) by rotating. A skip list gets it by flipping coins — each node picks its own height, and the tall ones form express lanes over the sorted list. No rotations, no rebalancing. Python or TypeScript.

YOUR TASK

Implement SkipList with insert(key), search(key), delete(key) and to_list() (toList()). Inserts of an existing key return False; so do deletes of a missing one. Use the supplied seeded coin flip so runs are reproducible.

HINTS — 7 IDEAS
  1. Every node carries an array of forward pointers — one per level it reaches. Level 0 is the full sorted list; higher levels skip more.
  2. A new node's height comes from repeated coin flips: keep flipping while heads, stop at tails. That gives level i about half the nodes of level i-1.
  3. Search, insert and delete all start the same way: walk down from the top level, moving right while the next key is smaller than the target. Record the last node visited on each level.
  4. That record is the update vector — the nodes whose pointers must be rewired on insert or delete. Building it once is why all three operations share one helper.
  5. After the walk, the candidate is always update[0].next[0]. It either equals the key or the key is absent — no other case exists.
  6. On delete, only rewire a level if that level actually points at the doomed node; a short node does not appear in the tall lanes.
  7. The height is random, not balanced — but the probability of a badly skewed list shrinks exponentially, which is why expected search cost stays O(log n).
CPython · WebAssembly

Keep going

▶  Watch it explained

Skip List: Time and Space Complexity, From First Principles

Finished this one? 0 / 99 Algorithms done
NextPiece Table & Rope: Edit Without Copying Next on the “Structures a database ships” ladder · rung 4 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms