Skip Lists
A skip list stacks sparser and sparser linked lists on top of a sorted one. Each upper lane skips ahead over the lane below, so a search moves right and drops down instead of walking every node: O(log n) expected, with coin flips doing the job rotations do in a balanced tree.
What Is a Skip List?
A sorted linked list is easy to keep in order but slow to search: there is no way to jump to the middle, so finding a key means following pointers one at a time, O(n).
A skip list adds lanes. The bottom lane, L0, is the full sorted list. Above it, L1 links roughly half the nodes, L2 roughly a quarter, and so on. Each lane is an express lane over the one below, like an express train that stops at fewer stations. William Pugh introduced the skip list data structure in 1990 as a simpler alternative to balanced trees.
A key that reaches level k is one node holding k forward pointers, one per lane, often drawn as a tower. With each lane about half the size of the one below there are about log₂ n lanes, which is where the O(log n) cost comes from.
- L0 holds every key in sorted order
- Each lane above holds about half the keys of the lane below
- A node is a tower of next pointers, one per level it reaches
Skip List Search
- Start at the head on the top lane
- While the next key on this lane is smaller than the target, move right
- When the next key is larger, or there is none, drop one lane at the same node
- After L0, look at the next node: it is the target, or the target is absent
Skip list search follows one rule: move right while you can, drop down when the next key overshoots. The path looks like a staircase from the top left to the target.
In the tracer's list of 10 to 90, finding 70 checks 40 (right), 80 (drop), 60 (right), 80 (drop), then 70: five comparisons where the plain list needs seven hops. On a large list each lane costs about 2 comparisons on average with p = 1/2, so the search takes about 2 log₂ n.
A miss ends at the node just before where the key would be, which is exactly where an insert must splice it in. Search, insert and delete all walk the same path.
- Same path for search, insert and delete
- A miss stops at the target's predecessor on every lane
Skip List Insertion and Deletion
- Search for the key, saving the last node visited on each lane (the update path)
- Flip a coin: on heads add one level and flip again; stop on tails or at the level cap
- Splice the new node into every lane it reaches, starting with L0
Skip list insertion never measures the shape of the list. With a fair coin a new node reaches L1 with probability 1/2, L2 with 1/4, level k with 1/2^k. That alone keeps each lane about half the size of the one below, on average, with no rotations or rebalancing.
Splicing uses the update path: on each lane the new node takes the saved node's next pointer, and the saved node now points to the new node. A node of height 2 costs four pointer writes.
Deletion searches the same way and points each saved predecessor past the node on every lane it reaches. Both are O(log n) expected, the cost of the search.
Two practical details. The probability need not be 1/2: p = 1/4, as Redis uses, gives fewer levels and fewer pointers per node at the cost of a few more steps per lane. And a level cap (Redis uses 32) stops a long run of heads from building a huge tower.
- Height from coin flips; no rebalancing
- A node must be linked on every lane it reaches, L0 above all, or search cannot find it
Terms, operations, and practical uses
Structure and layers
- Express LanesHigher layers in the skip list that contain fewer nodes, allowing traversal to skip over large sections of the bottom layer.
- Bottom LayerThe foundational layer (Layer 0) which is a standard sorted linked list containing every single inserted element.
- TowerThe vertical column of nodes representing a single element across multiple layers.
Algorithms
- Probabilistic BalancingFlipping a virtual coin to decide if a newly inserted node should be promoted to the next higher layer.
- Drop DownThe action of moving to a lower layer during a search when the next node in the current layer is greater than the target.
- Update ArrayAn array used during insertion to remember the right-most nodes visited at each layer so the new node can be spliced in correctly.
Comparisons and uses
- O(log N) ExpectedSearch, insert and delete take O(log n) on average over the coin flips; a run of very bad luck could make them O(n), but no input can force it.
- ConcurrencySkip lists are easier to make thread-safe than balanced trees because updates are highly localized and don't require global rotations.
- Redis Sorted SetsThe most famous real-world implementation of a skip list, used to rank elements quickly by score.
Code in Python, C++ and Java
import random
MAX_LEVEL = 3
class Node:
def __init__(self, key, height):
self.key = key
self.next = [None] * height
class SkipList:
def __init__(self):
self.head = Node(None, MAX_LEVEL)
def random_height(self):
height = 1
while height < MAX_LEVEL and random.random() < 0.5:
height += 1
return height
def search(self, key):
node = self.head
for level in range(MAX_LEVEL - 1, -1, -1):
while node.next[level] and node.next[level].key < key:
node = node.next[level]
node = node.next[0]
return node is not None and node.key == key
def insert(self, key, height=None):
height = height or self.random_height()
update = [self.head] * MAX_LEVEL
node = self.head
for level in range(MAX_LEVEL - 1, -1, -1):
while node.next[level] and node.next[level].key < key:
node = node.next[level]
update[level] = node
new = Node(key, height)
for level in range(height):
new.next[level] = update[level].next[level]
update[level].next[level] = new
def delete(self, key):
update = [self.head] * MAX_LEVEL
node = self.head
for level in range(MAX_LEVEL - 1, -1, -1):
while node.next[level] and node.next[level].key < key:
node = node.next[level]
update[level] = node
target = node.next[0]
if target is None or target.key != key:
return False
for level in range(len(target.next)):
update[level].next[level] = target.next[level]
return True
def lane(self, level):
keys, node = [], self.head.next[level]
while node:
keys.append(node.key)
node = node.next[level]
return keys
skip = SkipList()
# fixed heights so the run matches the tracer; real code calls random_height()
for key, height in zip(range(10, 100, 10), [1, 2, 1, 3, 1, 2, 1, 3, 1]):
skip.insert(key, height)
print("L2", skip.lane(2), "L1", skip.lane(1))
print("search 70:", skip.search(70), "search 65:", skip.search(65))
skip.insert(65, 2)
skip.delete(40)
print("after insert 65, delete 40: L1", skip.lane(1), "L0", skip.lane(0))#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
const int MAX_LEVEL = 3;
struct Node {
int key;
vector<Node*> next;
Node(int key, int height) : key(key), next(height, nullptr) {}
};
struct SkipList {
Node* head = new Node(0, MAX_LEVEL);
int randomHeight() {
int height = 1;
while (height < MAX_LEVEL && rand() % 2 == 0) height++;
return height;
}
// last node before key on every level
vector<Node*> findUpdate(int key) {
vector<Node*> update(MAX_LEVEL, head);
Node* node = head;
for (int level = MAX_LEVEL - 1; level >= 0; level--) {
while (node->next[level] && node->next[level]->key < key) node = node->next[level];
update[level] = node;
}
return update;
}
bool search(int key) {
Node* node = findUpdate(key)[0]->next[0];
return node != nullptr && node->key == key;
}
void insert(int key, int height = 0) {
if (height == 0) height = randomHeight();
vector<Node*> update = findUpdate(key);
Node* fresh = new Node(key, height);
for (int level = 0; level < height; level++) {
fresh->next[level] = update[level]->next[level];
update[level]->next[level] = fresh;
}
}
bool remove(int key) {
vector<Node*> update = findUpdate(key);
Node* target = update[0]->next[0];
if (target == nullptr || target->key != key) return false;
for (size_t level = 0; level < target->next.size(); level++)
update[level]->next[level] = target->next[level];
delete target;
return true;
}
vector<int> lane(int level) {
vector<int> keys;
for (Node* node = head->next[level]; node; node = node->next[level]) keys.push_back(node->key);
return keys;
}
};
void print(const vector<int>& keys) {
cout << "[";
for (size_t i = 0; i < keys.size(); i++) cout << (i ? ", " : "") << keys[i];
cout << "]";
}
int main() {
SkipList skip;
int heights[] = {1, 2, 1, 3, 1, 2, 1, 3, 1};
// fixed heights so the run matches the tracer; real code calls randomHeight()
for (int i = 0; i < 9; i++) skip.insert(10 * (i + 1), heights[i]);
cout << "L2 "; print(skip.lane(2)); cout << " L1 "; print(skip.lane(1)); cout << '\n';
cout << "search 70: " << (skip.search(70) ? "True" : "False")
<< " search 65: " << (skip.search(65) ? "True" : "False") << '\n';
skip.insert(65, 2);
skip.remove(40);
cout << "after insert 65, delete 40: L1 "; print(skip.lane(1));
cout << " L0 "; print(skip.lane(0)); cout << '\n';
}import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
static final int MAX_LEVEL = 3;
static class Node {
int key;
Node[] next;
Node(int key, int height) {
this.key = key;
this.next = new Node[height];
}
}
static class SkipList {
Node head = new Node(0, MAX_LEVEL);
Random random = new Random();
int randomHeight() {
int height = 1;
while (height < MAX_LEVEL && random.nextBoolean()) height++;
return height;
}
// last node before key on every level
Node[] findUpdate(int key) {
Node[] update = new Node[MAX_LEVEL];
Node node = head;
for (int level = MAX_LEVEL - 1; level >= 0; level--) {
while (node.next[level] != null && node.next[level].key < key) node = node.next[level];
update[level] = node;
}
return update;
}
boolean search(int key) {
Node node = findUpdate(key)[0].next[0];
return node != null && node.key == key;
}
void insert(int key, int height) {
if (height == 0) height = randomHeight();
Node[] update = findUpdate(key);
Node fresh = new Node(key, height);
for (int level = 0; level < height; level++) {
fresh.next[level] = update[level].next[level];
update[level].next[level] = fresh;
}
}
boolean delete(int key) {
Node[] update = findUpdate(key);
Node target = update[0].next[0];
if (target == null || target.key != key) return false;
for (int level = 0; level < target.next.length; level++)
update[level].next[level] = target.next[level];
return true;
}
List<Integer> lane(int level) {
List<Integer> keys = new ArrayList<>();
for (Node node = head.next[level]; node != null; node = node.next[level]) keys.add(node.key);
return keys;
}
}
public static void main(String[] args) {
SkipList skip = new SkipList();
int[] heights = {1, 2, 1, 3, 1, 2, 1, 3, 1};
// fixed heights so the run matches the tracer; real code passes 0 for a random height
for (int i = 0; i < 9; i++) skip.insert(10 * (i + 1), heights[i]);
System.out.println("L2 " + skip.lane(2) + " L1 " + skip.lane(1));
System.out.println("search 70: " + (skip.search(70) ? "True" : "False")
+ " search 65: " + (skip.search(65) ? "True" : "False"));
skip.insert(65, 2);
skip.delete(40);
System.out.println("after insert 65, delete 40: L1 " + skip.lane(1) + " L0 " + skip.lane(0));
}
}Step through it
Running on keys 10 20 30 40 50 60 70 80 90; heights 1 2 1 3 1 2 1 3 1
Expected, Not Guaranteed
A skip list is a probabilistic data structure: search, insert and delete are O(log n) expected. An AVL or red-black tree is O(log n) in the worst case. If every coin flip came up tails, every node would sit on L0 alone and the skip list would be a plain list, O(n).
The difference from an unbalanced binary search tree is who controls the bad case. A plain BST becomes a chain on sorted input, which is common. A skip list's shape depends only on the random flips, so no order of keys can force the bad case. The chance that the height exceeds c · log₂ n is at most about 1/n^(c−1), so long lists are the safest.
Space is O(n): with p = 1/2 a node holds 2 pointers on average (1 + 1/2 + 1/4 + …), with p = 1/4 about 1.33.
Because L0 is a complete sorted list, range queries are a search plus a walk along L0, much like the linked leaves of a B+ tree.
| Skip list | AVL / red-black tree | |
|---|---|---|
| Search, insert, delete | O(log n) expected | O(log n) worst case |
| Keeping it balanced | Coin flips, nothing to fix | Rotations and colour or height rules |
| Concurrent updates | Local pointer changes per lane | Rotations touch nodes far from the change |
| Pointers per node | About 2 (p = 1/2) | 2 children plus balance data |
- Bad luck, not bad input, is the only way to the O(n) case
- Range queries: search to the start, then walk L0
Where Skip Lists Are Used
The case for a skip list over a balanced tree rests on two things. Simplicity: a skip list is linked-list splicing plus a random height, with no case analysis, while red-black deletion is famously easy to get wrong. Concurrency: an insert changes only the predecessor pointers on its update path, so fine-grained locking and lock-free versions with compare-and-swap are practical.
That is why Java's ConcurrentSkipListMap is the standard library's concurrent sorted map. Redis stores sorted sets as a skip list plus a hash table: the hash gives O(1) score lookup by member, the skip list gives order for ranges and ranks. LevelDB and RocksDB keep their in-memory write buffer, the memtable, in a skip list, and Lucene uses skip lists to jump through long posting lists.
For a single-threaded sorted map a balanced tree is still the usual choice, which is why std::map and TreeMap are red-black trees. Related lessons: linked lists, binary search trees, red-black trees.
- Pick a skip list when concurrency or simple code matters more than a worst-case bound
- Used in ConcurrentSkipListMap, Redis sorted sets, LevelDB and RocksDB memtables