A skip list is a sorted linked list with express lanes: extra levels of pointers that skip over many nodes at once. Each node's height is chosen by flipping coins, so no rebalancing is ever needed, yet search, insert and delete all take O(log n) expected time. Skip lists are simpler to implement than balanced trees, friendly to concurrency, and they power Redis sorted sets and the in-memory write buffers of LevelDB and RocksDB.
Think of it like
Local and express trains
A subway line has a local train that stops at every station and an express train that stops only at major ones, maybe with a super-express above that. To reach a station, you ride the fastest line as far as you can without overshooting, then step down to a slower line for the last few stops. A skip list is that subway map for sorted keys, and the coin flips decide which stations become express stops.
How it works
Level 0 is an ordinary sorted linked list containing every key. Each higher level is a sorted sublist of the level below: a node that appears on level i appears on every level below it too. With promotion probability p = 1/2, about half the nodes reach level 1, a quarter reach level 2, and so on, so each level is roughly half the size of the one below.
L3: HEAD -------------------------------------> 50 -------------------------------> NIL
L2: HEAD -------------> 12 -------------------> 50 -------------------> 81 -------> NIL
L1: HEAD -------> 7 -> 12 -------> 25 -------> 50 -------> 63 -------> 81 -------> NIL
L0: HEAD -> 3 -> 7 -> 12 -> 19 -> 25 -> 31 -> 50 -> 57 -> 63 -> 72 -> 81 -> 90 -> NIL- Level
- One horizontal linked list. Level 0 holds every key; higher levels hold progressively fewer.
- Height (tower)
- The number of levels a node participates in, chosen randomly at insertion time.
- Forward pointers
- Each node stores
next[i]for every levelibelow its height. - Header
- A sentinel node with the maximum height and key −∞, so every search can start in the same place.
- p
- The probability of promoting a node one more level, typically 1/2 or 1/4.
Search
- 1
Start high
Begin at the header on the highest level currently in use.
- 2
Move right while you can
While the next node's key is less than the target, move to it.
- 3
Drop down
When the next key would be greater than or equal to the target (or is NIL), go down one level and repeat.
- 4
Check level 0
After the bottom level, the candidate is
cur.next[0]. The key is present exactly when that node's key equals the target.
| Level | At node | Next key | Action |
|---|---|---|---|
| L3 | HEAD | 50 | 50 < 63: move right to 50 |
| L3 | 50 | NIL | Drop down |
| L2 | 50 | 81 | 81 ≥ 63: drop down |
| L1 | 50 | 63 | 63 ≥ 63: drop down |
| L0 | 50 | 57 | 57 < 63: move right to 57 |
| L0 | 57 | 63 | Bottom reached: next[0] is 63, found |
Insert with coin flips
- 1
Search and remember
Run the search, but record in
update[i]the last node visited on each leveli. These are the nodes whose pointers will change. - 2
Flip coins
Start with height 1 and keep adding a level while a coin with probability p comes up heads, up to
MAX_LEVEL. - 3
Grow the list if needed
If the new height exceeds the current number of levels, set
update[i] = headerfor the new levels. - 4
Splice in
For each level below the new height:
node.next[i] = update[i].next[i], thenupdate[i].next[i] = node.
Delete
Search for the key while filling update[] exactly as for insertion. If update[0].next[0] holds the key, unlink it on every level where update[i].next[i] is that node, setting update[i].next[i] = node.next[i]. Finally, while the top level is empty, decrease the current level count so later searches do not start on empty lanes.
Why it is O(log n) expected
To bound the search cost, trace the search path backward from the bottom. At each node on the path, either the node also exists one level up (probability p), in which case the path came down from there, or it does not (probability 1 − p), in which case the path came from the left. So each climb of one level takes 1/p backward steps on average, and there are about log_{1/p} n levels to climb.
| p | Expected pointers per node | Expected search steps | Notes |
|---|---|---|---|
| 1/2 | 2 | ≈ 2 log₂ n | Classic textbook choice |
| 1/4 | ≈ 1.33 | ≈ 2 log₂ n | Pugh's recommendation; Redis and LevelDB use 1/4 |
| 1/e | ≈ 1.58 | ≈ 1.88 log₂ n | Minimizes the expected search cost |
Space is O(n) expected: the total number of forward pointers is n / (1 - p), about 2n for p = 1/2.
Skip lists vs balanced BSTs
Skip list
- O(log n) expected for search, insert and delete
- No rotations; about 100 lines of simple code
- Range scans are a walk along level 0
- Local updates make lock-free concurrent versions practical
- Pointer-heavy and less cache-friendly than B-trees
Balanced BST (AVL, red-black)
- O(log n) worst case guarantees
- Rebalancing logic is intricate and easy to get wrong
- In-order traversal for range scans
- Rotations touch several nodes, which complicates concurrency
- Usually the default ordered map in standard libraries
See Red-Black Trees and AVL Trees for the tree side of this trade-off, and B-Trees & B+ Trees for the disk-friendly alternative used by databases.
Why concurrency loves skip lists
Inserting into a skip list changes only the predecessors' pointers on each level, and those changes can be made one level at a time from the bottom up. Level 0 alone defines membership, so a node is "in" the list once it is linked there; the upper levels are just hints that speed up search. That makes it possible to insert with a compare-and-swap per level and no global lock, and readers never block.
- Java's
ConcurrentSkipListMapandConcurrentSkipListSetare lock-free skip lists and the standard concurrent sorted map on the JVM. - Concurrent balanced trees need rotations that touch several nodes atomically, which is much harder to do without locks.
- Deletion in lock-free skip lists marks a node logically deleted first, then unlinks it level by level.
Skip lists in production
| System | Use | Details |
|---|---|---|
| Redis sorted sets (ZSET) | Ordered members with scores | A skip list plus a hash table (member → score). p = 1/4, max level 32. Each forward pointer stores a span so ZRANK and index-based ZRANGE run in O(log n). |
| LevelDB | MemTable (in-memory write buffer) | A skip list with branching factor 4 and max height 12; supports concurrent readers with a single writer. |
| RocksDB | Default MemTable | Skip list by default, with alternatives such as hash-based and vector memtables. |
| Java | ConcurrentSkipListMap | Lock-free, sorted, navigable concurrent map. |
Implementation tips
- Give the header
MAX_LEVELpointers up front (16 to 32 is plenty for billions of keys with p = 1/2 or 1/4) and cap random heights at that value. - Track the current number of levels in use so searches skip empty upper lanes.
- Use a strict
<comparison while moving right, so the search stops just before the first key ≥ target. - Decide the duplicate policy: Redis allows equal scores and orders them by member; Design Skiplist allows duplicate numbers.
- In garbage-collected languages, deleting is just unlinking; in C++ remember to free nodes (or use smart pointers).
Complexity
| Operation | Expected | Worst case | Notes |
|---|---|---|---|
| Search | O(log n) | O(n) | Worst case requires extraordinarily unlucky coin flips |
| Insert | O(log n) | O(n) | Search plus O(height) splicing |
| Delete | O(log n) | O(n) | Search plus O(height) unlinking |
| Range query (k results) | O(log n + k) | O(n) | Find the start, then walk level 0 |
| Space | O(n) | O(n · MAX_LEVEL) | About n / (1 − p) pointers in expectation |
Expectations are over the random heights, so they hold for every input order.
Implementation
A complete skip list with a sentinel header, random heights (p = 1/2) and an `update` array of predecessors. Duplicates are allowed; erase removes one occurrence.
import random
MAX_LEVEL = 16
P = 0.5
class Node:
def __init__(self, key: float, level: int):
self.key = key
self.next: list["Node | None"] = [None] * level
class SkipList:
def __init__(self) -> None:
self.head = Node(float("-inf"), MAX_LEVEL)
self.level = 1 # levels currently in use
def _random_level(self) -> int:
lvl = 1
while lvl < MAX_LEVEL and random.random() < P:
lvl += 1
return lvl
def _predecessors(self, key: float) -> list[Node]:
update = [self.head] * MAX_LEVEL
cur = self.head
for i in range(self.level - 1, -1, -1):
nxt = cur.next[i]
while nxt is not None and nxt.key < key: # move right while smaller
cur, nxt = nxt, nxt.next[i]
update[i] = cur # last node before key on level i
return update
def search(self, key: float) -> bool:
cand = self._predecessors(key)[0].next[0]
return cand is not None and cand.key == key
def add(self, key: float) -> None:
update = self._predecessors(key)
lvl = self._random_level()
if lvl > self.level: # new levels start at the header
self.level = lvl
node = Node(key, lvl)
for i in range(lvl):
node.next[i] = update[i].next[i]
update[i].next[i] = node
def erase(self, key: float) -> bool:
update = self._predecessors(key)
target = update[0].next[0]
if target is None or target.key != key:
return False
for i in range(self.level):
if update[i].next[i] is target:
update[i].next[i] = target.next[i]
while self.level > 1 and self.head.next[self.level - 1] is None:
self.level -= 1 # drop empty top lanes
return True
def range(self, lo: float, hi: float) -> list[float]:
out, cur = [], self._predecessors(lo)[0].next[0]
while cur is not None and cur.key <= hi: # walk level 0
out.append(cur.key)
cur = cur.next[0]
return outKey takeaways
- A skip list is a sorted linked list plus randomly built express lanes; level 0 holds every key.
- Search moves right while the next key is smaller, then drops down: O(log n) expected steps.
- Insert records the predecessor on each level, flips coins for the height, and splices the node in; no rebalancing.
- Expected space is n / (1 − p) pointers; p = 1/4 saves memory with about the same search cost as p = 1/2.
- Simplicity, cheap range scans and lock-free concurrency explain its use in Redis sorted sets, LevelDB/RocksDB memtables and Java's ConcurrentSkipListMap.
Common pitfalls
- Claiming O(log n) worst case: the bound is expected (with high probability), and the worst case is O(n).
- Forgetting to initialize
update[i]to the header for levels above the current height before splicing a tall node. - Using
<=while moving right, which skips past equal keys and breaks search and delete. - Not lowering the current level after deletions, leaving searches to start on empty lanes.
- Using a predictable or poorly seeded RNG in an adversarial setting.
Interview tips
- Draw the levels and trace a search as a staircase; it explains the algorithm faster than code.
- Explain the backward-analysis intuition: each level climb costs 1/p expected steps, over log_{1/p} n levels.
- Compare with red-black trees on code complexity, worst-case guarantees, range scans and concurrency.
Real-world applications
- Redis sorted sets for leaderboards, rate-limiter windows and priority queues.
- MemTables in LSM-tree storage engines (LevelDB, RocksDB) before data is flushed to SSTables.
- Concurrent ordered maps and sets (Java's ConcurrentSkipListMap).
- In-memory database indexes where lock-free concurrent access matters.
Practice problems
Test yourself
What is the expected time to search a skip list with n keys?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.