Skip lists
The conceptHow a sorted list of a million names can be searched in about 20 hops
A skip list is a sorted linked list with express lanes stacked on top. In a plain linked list, each item points only to the next one, so finding one name among a million can mean walking through most of them.
When an item is added, the skip list flips a coin. On heads, the item also joins the lane above, and it keeps flipping until it gets tails. The bottom lane holds every item, the next about half, the next about a quarter, and so on.
To search, you start in the top lane and move right while the next item is still smaller than your target. Then you drop down a lane and repeat until you land on the item.
What it’s forGives the chance that a new item reaches a given lane, which decides how many express lanes form.
P(level ≥ L) = p^(L−1)
- p
- chance of moving up one more lane, usually 1/2 (one coin flip)
- L
- the lane number, with 1 as the bottom lane
- P
- share of items that appear in lane L or higher
What it givesEach lane up holds about p times as many items, so there are about log₁/ₚ(n) lanes in total.
- p = 1/2, L = 3: P = (1/2)² = 1/4
- 1,000,000 items × 1/4 ≈ 250,000 reach lane 3
- 2²⁰ ≈ 1,000,000, so about 20 lanes in total