A skip list is a sorted linked list with express lanes. Every key sits in the bottom lane, a random quarter of the keys are promoted one lane up, a quarter of those again, and so on. The upper lanes are sparse enough to cover ground fast and dense enough to land near any target before the search drops down. The result is a sorted container with expected O(log n) search, insertion and deletion, built from arrays of forward pointers with no rotations. At 100,000 keys, the measured level counts matched the expected quarter-per-level split, and a lookup averaged 29.906 key comparisons against 15.689 for an AVL tree.
This guide covers the node towers, the search path, insertion and deletion across lanes, the random level generator and the expected cost that follows from it. It then measures the level distribution against theory and the lookup cost against a balanced tree, and closes with the Redis sorted set that made the structure famous. The AVL Tree and Red-Black Tree articles cover the balanced trees it competes with. The code was built and tested with GCC 13.3, Clang 18.1.3 and MSVC 19.44, and both languages print byte-identical output.
What Is a Skip List?
A skip list is a sorted linked list in which each node carries a tower of forward pointers, with tower heights chosen at random: level 1 holds every key, level 2 an expected fraction p of them, level 3 a fraction p squared, and so on. A search starts on the top level of a head node, moves right while the next key is smaller, drops a level when it would overshoot, and finishes on level 1.
William Pugh published the structure in 1990 as a probabilistic alternative to balanced trees. A balanced tree guarantees O(log n) by rebalancing on every update, which costs rotations and balance state. A skip list reaches the same expected bound by choosing levels at random, which costs a random number and a few pointer updates per insertion. Because the levels come from a random generator rather than from the keys, no insertion order can produce a bad shape. Only an unlucky run of random draws can, and the chance of that falls exponentially with the length of the run.
Each node stores a key and an array of forward pointers, one per lane it belongs to. The head node has a pointer on every lane. Insertion searches like a lookup, gives the new node a random level and splices it into each lane between the last smaller node and its successor. Deletion splices the node out of every lane, frees it and lowers the list’s top level while the head’s top pointer is empty. There are no rotations, no parent pointers and no rebalancing passes.
How This Was Measured
| Setting | Value |
|---|---|
| Date tested | December 2, 2026 |
| Hardware | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300 |
| Operating system | Ubuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39, and Windows 11 for the MSVC build |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 through CMake Release, MSVC 19.44 at /W4 /WX |
| Level generator | xorshift64 with seed 88172645463325252. Level 1, plus one level for each (next() & 3) == 0 in a row, capped at 32 |
| Level experiment | 100,000 ascending insertions. Node counts at or above levels 1 to 12, against p^(k-1) with p = 1/4 |
| Lookup experiment | N of 1,000, 10,000 and 100,000. Every key searched once in the skip list and in an insert-only AVL tree |
| Statistic | Node counts and fractions, and average key comparisons per successful lookup, with the maximum level and the AVL height |
| Check | The same seed and operation sequence in both languages, which must print identical tables |
The numbers are deterministic for the seed, so both languages produce the same tables. Both structures count key comparisons. The skip list counts one for every next key it inspects, including the one that sends it down a lane, and the AVL tree counts one for every node it visits.
The Layered Structure
A node of level L appears on lanes 1 through L and has L forward pointers. The list keeps its current top level, its size and its random state. The bottom lane is a complete sorted linked list of every key, so an in-order traversal or a range scan just follows level 1.
The towers make the search fast. Each lane is a sample of the lane below, spaced further apart the higher it is. A step to the right on lane k skips an expected 1/p keys of lane k – 1, and descending one lane at a time combines the long steps of the sparse lanes with the precision of the dense ones.
The layout is deliberately simple: no parent pointers, colors, heights or rotations, and a node costs its forward array plus the key. An insertion changes one pointer per lane of the new node. Because updates stay that local, lock-free versions are practical, and Java ships one as ConcurrentSkipListMap, where a lock-free balanced tree would need a far more intricate protocol.
Search: One Pass Down the Levels
The search starts on the head’s top lane and repeats one rule: move right while the next node exists and its key is smaller than the target, then drop one lane. On level 1, the next node either holds the target or proves it is absent. The path only moves right or down, so it cannot loop.
Each lane costs about 1/p comparisons, the right moves plus the one inspection that sends the search down, and there are about log_{1/p} n lanes. With p = 1/4 that is 4 comparisons per lane over log4 n lanes, about 2 log2 n in total. That predicts about 33 comparisons at 100,000 keys against the measured 29.9, while a balanced tree needs about log2 n.
Insert and Delete: Updating the Towers
Insertion begins with the same descent, but it records the last node visited on each lane in an update array. If the key is already present, the insert returns false and allocates nothing. Otherwise it draws a level and links a new node into every lane from 1 to that level: the new node takes over the update node’s old forward pointer on that lane, and the update node points at the new node. If the new level is above the list’s current top, the head’s pointers on the new lanes point at the new node and the list’s top level grows.
Deletion fills the same update array to find the node and its predecessor on every lane. It splices the node out of each lane, frees it, and lowers the list’s top level while the head’s top pointer is empty. Both operations touch one pointer per lane of the node, an expected 1/(1 – p) pointers, so the pointer work is O(1) on average and the search dominates at O(log n).
The update array is where most implementations go wrong. It must be filled on every lane during the descent, and every lane of the node must be relinked during the splice. Two of the pitfalls below break exactly that: a deletion that unlinks only the bottom lane, and an insertion that leaves one lane pointing at the old successor.
Probability, Levels and the Expected Cost
With promotion probability p, a node reaches level k with probability p^(k-1), so the expected number of nodes on level k is n p^(k-1) and the expected number of levels is log_{1/p} n. A smaller p makes each lane sparser and adds lanes. A larger p makes towers shorter and lanes denser. The search cost works out to about (1/p) / log2(1/p) times log2 n, which is exactly 2 log2 n for both p = 1/2 and p = 1/4. The quarter needs fewer pointers for the same search cost, about 1.33 per node against 2, which is why Pugh recommends it and Redis uses it.
The level cap protects the array bounds: without it, an unlucky run of promotions could ask for a tower taller than the node’s array. The implementation caps towers at 32 levels, far above the expected log4 n, about 10 at a million keys. The cap therefore changes nothing in expectation and turns a vanishingly rare overflow into an impossible one.
Redis stores larger sorted sets as a skip list paired with a hash table from member to score, while small ones stay in a compact list. The Redis sorted-set documentation describes the operations, and Pugh’s 1990 paper and the Wikipedia article give the analysis. Redis’s reasons are the ones in this section: expected logarithmic search, simple local updates and ordered traversal for range queries by score.
Skip List vs Balanced Trees
A balanced tree guarantees O(log n) in the worst case and stores balance state, a height or a color, in every node. A skip list gives O(log n) in expectation and stores about 1/(1 – p) forward pointers per node on average, 1.33 at p = 1/4. The simple implementation here gives every node a fixed 32-pointer array instead, which trades memory for code that is easy to read. Per lookup, a balanced tree makes about log2 n comparisons and the skip list about twice that, which is what the measurement shows.
The stronger case for skip lists is engineering rather than asymptotics. Ordered traversal is a linked-list walk, range queries are natural, insertion touches few pointers, and concurrent versions are practical because updates stay local. The stronger case for trees is the worst-case guarantee, fewer comparisons per lookup and compact nodes. The article measures both costs and leaves the choice to the workload.
Skip List Implementation in C
The C version is a struct with a head node whose forward array has one pointer per level, plus the current level, the size, the random state and a comparison counter. Every node gets a fixed 32-pointer array, which keeps the towers and the cap easy to see at the price of memory.
static int sl_random_level(SkipList *list)
{
int level = 1;
while (level < SKIP_LIST_MAX_LEVEL && (sl_next(list) & 3ULL) == 0)
++level;
return level;
}
bool sl_insert(SkipList *list, int key)
{
SkipNode *update[SKIP_LIST_MAX_LEVEL] = {NULL};
SkipNode *fresh;
int new_level;
int index;
if (list->head == NULL)
return false;
sl_search_links(list, key, update);
if (update[0]->forward[0] != NULL && update[0]->forward[0]->key == key)
return false;
new_level = sl_random_level(list);
fresh = sl_new_node(key, (unsigned char)new_level);
if (fresh == NULL)
return false;
if (new_level > list->level) {
for (index = list->level; index < new_level; ++index)
update[index] = list->head;
list->level = new_level;
}
for (index = 0; index < new_level; ++index) {
fresh->forward[index] = update[index]->forward[index];
update[index]->forward[index] = fresh;
}
list->size++;
return true;
}
bool sl_erase(SkipList *list, int key)
{
SkipNode *update[SKIP_LIST_MAX_LEVEL] = {NULL};
SkipNode *victim;
int index;
if (list->head == NULL)
return false;
sl_search_links(list, key, update);
victim = update[0]->forward[0];
if (victim == NULL || victim->key != key)
return false;
for (index = 0; index < list->level; ++index) {
if (update[index]->forward[index] == victim)
update[index]->forward[index] = victim->forward[index];
}
free(victim);
list->size--;
while (list->level > 1 && list->head->forward[list->level - 1] == NULL)
--list->level;
return true;
}
Output:
skip list: insert, search and delete
insert 3, 1, 2 -> size 3, min 1, max 3
search 2 -> true, search 4 -> false
insert 5, 4 -> size 5
inorder: 1 2 3 4 5
delete 3 -> true, size 4
search 3 -> false, min 1, max 5
inorder: 1 2 4 5
delete 99 -> false, size 4, all checks pass
Skip List Implementation in C++
The C++ version is a class with the same layout: a head node, nodes with a fixed array of forward pointers, a random state seeded in the constructor, and the same operations and counters. The demo prints the same lines as the C program, byte for byte.
bool insert(int key)
{
Node* update[kMaxLevel];
Node* node = record_update_path(key, update);
if (node->forward[0] != nullptr && node->forward[0]->key == key)
return false; // duplicate: the level stream is not consumed
const int new_level = generate_level();
if (new_level > level_) {
for (int level = level_; level < new_level; ++level)
update[level] = &head_;
level_ = new_level;
}
Node* fresh = new Node(key, new_level);
for (int level = 0; level < new_level; ++level) {
fresh->forward[level] = update[level]->forward[level];
update[level]->forward[level] = fresh;
}
++size_;
return true;
}
bool erase(int key)
{
Node* update[kMaxLevel];
Node* node = record_update_path(key, update);
Node* target = node->forward[0];
if (target == nullptr || target->key != key)
return false;
for (int level = 0; level < static_cast<int>(target->level); ++level)
update[level]->forward[level] = target->forward[level];
delete target;
--size_;
while (level_ > 1 && head_.forward[level_ - 1] == nullptr)
--level_;
return true;
}
[[nodiscard]] std::size_t size() const noexcept { return size_; }
Node* record_update_path(int key, Node* update[kMaxLevel]) noexcept
{
Node* node = &head_;
for (int level = level_ - 1; level >= 0; --level) {
while (node->forward[level] != nullptr) {
++comparisons_;
if (node->forward[level]->key < key)
node = node->forward[level];
else
break;
}
update[level] = node;
}
return node;
}
Measured: Level Distribution
The level experiment inserts the keys 0 to 99,999 in ascending order with the fixed seed and counts the nodes at or above each level. It compares each measured fraction with p^(k-1).
int main(void)
{
SkipList list;
const SkipNode *node;
int counts[LEVELS_PRINTED];
int level;
int key;
size_t nodes = 0;
double theory = 1.0;
bool ok = true;
if (!sl_init(&list)) {
fputs("level_experiment: out of memory\n", stderr);
return EXIT_FAILURE;
}
for (key = 0; key < ELEMENTS; ++key) {
if (!sl_insert(&list, key)) {
fputs("level_experiment: insert failed\n", stderr);
sl_free(&list);
return EXIT_FAILURE;
}
}
for (level = 0; level < LEVELS_PRINTED; ++level)
counts[level] = 0;
for (node = list.head->forward[0]; node != NULL; node = node->forward[0]) {
nodes++;
for (level = 0; level < (int)node->level; ++level)
counts[level]++;
}
if (nodes != (size_t)ELEMENTS || sl_size(&list) != (size_t)ELEMENTS)
ok = false;
if (list.level < 1 || list.level > SKIP_LIST_MAX_LEVEL)
ok = false;
if (counts[0] != ELEMENTS)
ok = false;
for (level = 1; level < LEVELS_PRINTED; ++level) {
if (counts[level] > counts[level - 1])
ok = false;
}
puts("level distribution: N=100000, p=0.25, max level 32");
printf("%-7s%-9s%-10s%s\n", "level", "nodes", "measured", "theory");
for (level = 1; level <= LEVELS_PRINTED; ++level) {
printf("%-7d%-9d%-10.6f%.6f\n", level, counts[level - 1],
(double)counts[level - 1] / (double)ELEMENTS, theory);
theory *= 0.25;
}
sl_free(&list);
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
Output (C, identical in C++):
level distribution: N=100000, p=0.25, max level 32
level nodes measured theory
1 100000 1.000000 1.000000
2 25248 0.252480 0.250000
3 6266 0.062660 0.062500
4 1550 0.015500 0.015625
5 390 0.003900 0.003906
6 92 0.000920 0.000977
7 24 0.000240 0.000244
8 10 0.000100 0.000061
9 1 0.000010 0.000015
10 0 0.000000 0.000004
11 0 0.000000 0.000001
12 0 0.000000 0.000000
The measured counts track the theory closely. Level 2 holds 25,248 nodes, a fraction of 0.252480 against 0.250000. Level 3 is 0.062660 against 0.062500, level 4 is 0.015500 against 0.015625 and level 5 is 0.003900 against 0.003906. The deep levels wobble around their small expected counts, as sampling noise does. The zeros at levels 10 to 12 are real measurements: each expects less than one node at this size, so a run with none is the likely outcome. The tallest tower is 9 against an expected log4(100,000) of about 8.3, which is normal for a geometric variable.
Measured: Lookups Against AVL
The lookup experiment builds a skip list and an insert-only AVL tree from the same keys and searches every key once in each, counting key comparisons.
static bool run_size(int n)
{
SkipList skip;
AvlNode *avl = NULL;
int key;
size_t skip_comparisons = 0;
size_t avl_comparisons = 0;
int skip_max_level = 0;
int avl_tree_height;
bool ok = true;
if (!sl_init(&skip))
out_of_memory();
for (key = 0; key < n; ++key) {
if (!sl_insert(&skip, key))
ok = false;
}
if (ok) {
sl_reset_comparisons(&skip);
for (key = 0; key < n; ++key) {
if (!sl_contains(&skip, key))
ok = false;
}
skip_comparisons = sl_comparisons(&skip);
skip_max_level = sl_max_level(&skip);
}
sl_free(&skip);
for (key = 0; key < n; ++key)
avl = avl_insert(avl, key);
for (key = 0; key < n; ++key) {
if (!avl_contains(avl, key, &avl_comparisons))
ok = false;
}
avl_tree_height = avl_height(avl);
avl_free(avl);
if (!ok || skip_max_level < 1 || skip_max_level > SKIP_LIST_MAX_LEVEL ||
skip_comparisons == 0 || avl_comparisons == 0)
return false;
printf("%-9d%-10.3f%-9.3f%-16d%d\n", n,
(double)skip_comparisons / (double)n,
(double)avl_comparisons / (double)n, skip_max_level,
avl_tree_height);
return true;
}
int main(void)
{
static const int sizes[] = {1000, 10000, 100000};
size_t index;
puts("lookups: every key searched once");
printf("%-9s%-10s%-9s%-16s%s\n", "N", "skip_cmp", "avl_cmp",
"skip_max_level", "avl_height");
for (index = 0; index < sizeof sizes / sizeof sizes[0]; ++index) {
if (!run_size(sizes[index])) {
fprintf(stderr, "lookup_experiment: N=%d produced no row\n",
sizes[index]);
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
Output (C, identical in C++):
lookups: every key searched once
N skip_cmp avl_cmp skip_max_level avl_height
1000 17.873 8.987 5 9
10000 23.173 12.363 8 13
100000 29.906 15.689 9 16
The skip list averages 17.873, 23.173 and 29.906 comparisons per successful lookup at the three sizes, and the AVL tree 8.987, 12.363 and 15.689, with heights of exactly floor(log2 N) for ascending input. The ratio stays close to two at every size, which is what the analysis predicts: about 2 log2 n comparisons for a p = 1/4 skip list against about log2 n for a balanced tree. That is the expected trade, not a defect. The skip list’s advantages are its update path, ordered traversal and concurrency, not its comparison count.
Five Ways a Skip List Passes a Quick Test and Still Fails
Each program below compiles cleanly and prints something plausible until the wrong value appears or a sanitizer stops it. The three C pitfalls are in the C repository and the two C++ pitfalls in the C++ repository, and the workflows rerun each one and check its output line or its sanitizer summary.
1. A Search That Skips the Bottom Lane
static bool search_misses_level(const Node *head, int list_level, int key)
{
const Node *node = head;
int level;
for (level = list_level - 1; level > 0; --level) {
while (node->forward[level] != NULL &&
node->forward[level]->key < key) {
node = node->forward[level];
}
}
return node->forward[0] != NULL && node->forward[0]->key == key;
}
/* The fix: walk right on every level, down to and including level 0. */
static bool search_correct(const Node *head, int list_level, int key)
{
const Node *node = head;
int level;
for (level = list_level - 1; level >= 0; --level) {
while (node->forward[level] != NULL &&
node->forward[level]->key < key) {
node = node->forward[level];
}
}
return node->forward[0] != NULL && node->forward[0]->key == key;
}
Output:
search_misses_level: the search stops after level 1 and misses the bottom level
level 1: 30
level 0: 10 20 30 40
wrong search 20 -> false
correct search 20 -> true
wrong search 30 -> false
correct search 30 -> true
The broken search loops while (level > 0) instead of walking down through level 0, so the bottom lane is never inspected. On a hand-built two-level list, the searches for 20 and 30 return false, while the correct function returns true for both. The descent must include the bottom level, and the loop condition is where that boundary lives.
2. A Delete That Leaves Dangling Lanes
static bool buggy_erase(Node *head, int key)
{
Node *node = head;
Node *victim;
while (node->forward[0] != NULL && node->forward[0]->key < key)
node = node->forward[0];
victim = node->forward[0];
if (victim == NULL || victim->key != key)
return false;
node->forward[0] = victim->forward[0];
free(victim);
return true;
}
/* The search that walks the stale level-1 pointer. */
static bool buggy_search(Node *head, int list_level, int key)
{
Node *node = head;
int level;
for (level = list_level - 1; level >= 0; --level) {
while (node->forward[level] != NULL &&
node->forward[level]->key < key) {
node = node->forward[level];
}
}
return node->forward[0] != NULL && node->forward[0]->key == key;
}
Output:
delete_leaves_dangling: erase unlinks the node only at level 0 and frees it
level 1: 20 40
level 0: 10 20 30 40
delete 20 -> true, size 3
after the broken delete, level 0 is relinked but the level-1 chain still points at the freed node 20
level 0: 10 30 40
search 40 -> reading the freed level-1 pointer
AddressSanitizer stops the next search. Its report, summarized:
ERROR: AddressSanitizer: heap-use-after-free
READ of size 4 in buggy_search (pitfalls/delete_leaves_dangling.c:76)
0 bytes inside a 24-byte region freed by buggy_erase (pitfalls/delete_leaves_dangling.c:64)
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/delete_leaves_dangling.c:76 in buggy_search
The broken erase unlinks the node from level 0 only and frees it, so the higher lanes still point at the freed node. A later search that descends through level 1 reads the freed key, and AddressSanitizer reports a heap-use-after-free read in the search, with the 24-byte node freed in the erase. Every lane that points at a node must be relinked before the node is freed, which is what the update array is for.
3. A Forward Array Off by One
static void buggy_setup_forward(Node *node)
{
int index;
for (index = 0; index <= node->level; ++index)
node->forward[index] = NULL;
}
int main(void)
{
Node *node;
setvbuf(stdout, NULL, _IONBF, 0);
puts("forward_array_off_by_one: a node with level 2 allocates 2 forward "
"entries");
node = node_new(20, 2);
printf("node %d: level %d, forward array of %d entries\n", node->key,
node->level, node->level);
puts("the setup loop is written as index <= level, so it writes "
"forward[2], one past the array");
buggy_setup_forward(node);
puts("the write past the array did not fail loudly");
free(node->forward);
free(node);
return EXIT_SUCCESS;
}
Output:
forward_array_off_by_one: a node with level 2 allocates 2 forward entries
node 20: level 2, forward array of 2 entries
the setup loop is written as index <= level, so it writes forward[2], one past the array
AddressSanitizer stops the setup loop. Its report, summarized:
ERROR: AddressSanitizer: heap-buffer-overflow
WRITE of size 8 in buggy_setup_forward (pitfalls/forward_array_off_by_one.c:55)
0 bytes after a 16-byte region allocated by node_new (pitfalls/forward_array_off_by_one.c:43)
SUMMARY: AddressSanitizer: heap-buffer-overflow pitfalls/forward_array_off_by_one.c:55 in buggy_setup_forward
The node’s forward array is allocated with level entries, but the setup loop writes level + 1, so the last write lands one pointer past a 16-byte array. AddressSanitizer reports a heap-buffer-overflow write of size 8 right after the allocation. Allocate as many pointers as the loop writes, or loop to the allocated length, so the two always match.
4. A Stale Forward Pointer
void insert(int key, int new_level, bool stale)
{
Node* update[kMaxLevel];
Node* node = &head;
for (int level = level_ - 1; level >= 0; --level) {
while (node->forward[level] != nullptr && node->forward[level]->key < key)
node = node->forward[level];
update[level] = node;
}
if (new_level > level_) {
for (int level = level_; level < new_level; ++level)
update[level] = &head;
level_ = new_level;
}
Node* fresh = new Node(key, new_level);
owned_.push_back(fresh);
for (int level = 0; level < new_level; ++level) {
fresh->forward[level] = update[level]->forward[level];
if (!(stale && level == 0))
update[level]->forward[level] = fresh;
}
++size_;
}
int main()
{
std::cout << "stale_forward_pointer: the insert leaves the level-0 link at the old "
"successor\n";
// Key 4 is promoted to level 2, key 2 is the level-1 predecessor and key 5 is
// the old level-0 successor of key 3.
const int keys[] = {1, 2, 3, 5, 4};
const int levels[] = {1, 2, 1, 1, 2};
List correct;
List buggy;
for (int i = 0; i < 5; ++i) {
correct.insert(keys[i], levels[i], false);
// Only the insert of key 4 is broken: it writes the level-1 link but
// leaves the level-0 predecessor pointing at key 5.
buggy.insert(keys[i], levels[i], keys[i] == 4);
}
print_keys("correct inorder:", correct.keys());
print_keys("buggy inorder:", buggy.keys());
std::cout << "correct size: " << correct.size() << ", buggy size: " << buggy.size() << '\n';
std::cout << "correct search 4 -> " << (correct.contains(4) ? "true" : "false")
<< ", buggy search 4 -> " << (buggy.contains(4) ? "true" : "false") << '\n';
std::cout << "correct search 5 -> " << (correct.contains(5) ? "true" : "false")
<< ", buggy search 5 -> " << (buggy.contains(5) ? "true" : "false") << '\n';
std::cout << "violated invariant: every level must relink the predecessor to the new node\n";
return EXIT_SUCCESS;
}
Output:
stale_forward_pointer: the insert leaves the level-0 link at the old successor
correct inorder: 1 2 3 4 5
buggy inorder: 1 2 3 5
correct size: 5, buggy size: 5
correct search 4 -> true, buggy search 4 -> false
correct search 5 -> true, buggy search 5 -> true
violated invariant: every level must relink the predecessor to the new node
The insertion updates the higher lanes but leaves the level-0 link pointing at the old successor. The in-order traversal shows 1 2 3 5, the size still says 5, and a search for 4 returns false even though the node exists and is counted. Every lane must relink its predecessor to the new node, and one stale lane is enough to make the structure contradict itself.
5. A Duplicate That Gets Stored
bool insert(int key, bool reject_duplicates)
{
Node* node = &head;
while (node->forward[0] != nullptr && node->forward[0]->key < key)
node = node->forward[0];
if (reject_duplicates && node->forward[0] != nullptr && node->forward[0]->key == key)
return false;
Node* fresh = new Node(key);
fresh->forward[0] = node->forward[0];
node->forward[0] = fresh;
++size_;
return true;
}
int main()
{
std::cout << "duplicate_insert: the insert does not reject a key that is already present\n";
const int keys[] = {2, 1, 2, 3};
List correct;
List buggy;
for (const int key : keys) {
correct.insert(key, true);
buggy.insert(key, false); // the missing duplicate check
}
print_keys("correct inorder:", correct.keys());
print_keys("buggy inorder:", buggy.keys());
std::cout << "correct size: " << correct.size() << ", buggy size: " << buggy.size() << '\n';
std::cout << "correct key 2 count: " << correct.count(2)
<< ", buggy key 2 count: " << buggy.count(2) << '\n';
std::cout << "violated invariant: insert must reject a key that is already present\n";
return EXIT_SUCCESS;
}
Output:
duplicate_insert: the insert does not reject a key that is already present
correct inorder: 1 2 3
buggy inorder: 1 2 2 3
correct size: 3, buggy size: 4
correct key 2 count: 1, buggy key 2 count: 2
violated invariant: insert must reject a key that is already present
The insertion does not reject a key that is already present, so inserting 2 twice creates a second node with the same key. The in-order sequence becomes 1 2 2 3 and the size becomes 4 against the correct 3. A sorted set is a set: the duplicate check belongs in the descent, before the node is allocated, and the boolean return value is part of the contract.
Key Takeaways
- A skip list is a sorted linked list with towers of forward pointers. Level 1 holds every key, and each higher level holds an expected fraction p of the level below.
- A search moves right while the next key is smaller and drops a lane otherwise, in expected O(log n) time with no rotations.
- Insertion and deletion fill an update array during the descent and relink one pointer per lane, O(1) expected pointer work.
- At 100,000 keys, the measured level-2 fraction was 0.252480 against the expected 0.250000, and the tallest tower was 9 levels.
- A lookup averaged 29.906 comparisons against 15.689 for an AVL tree, close to the predicted factor of two for p = 1/4.
- Redis uses skip lists for larger sorted sets because they give expected logarithmic search, ordered traversal and simple, range-friendly updates.
Frequently Asked Questions
Conclusion
The skip list is a small piece of probabilistic engineering with a large payoff in simplicity. Towers of forward pointers, a random promotion per insertion and an update array are enough for expected logarithmic search, insertion and deletion with no rotations and no balance state. The measured level distribution lands where theory says it should. The measured lookups show the trade honestly: at 100,000 keys the skip list needed 29.906 comparisons per lookup against AVL’s 15.689, while it keeps the simpler updates, ordered traversal and concurrent variants that made it the basis of Redis sorted sets.
The data structures hub places the skip list beside the trees. In production, use the standard ordered container unless the workload is range-heavy or concurrent. When you write the list yourself, keep the level cap, the update array and the duplicate rule under test, because the pitfalls above show how quietly a lane can go stale.
Source Code and Tests
The programs on this page are in the data-structures/skip-list directory of two MYCPLUS example repositories:
| Language | Repository directory | Build status |
|---|---|---|
| C | mycplus/c-examples: data-structures/skip-list | |
| C++ | mycplus/cpp-examples: data-structures/skip-list |
The examples build and test with CMake:
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
The demo’s output is compared byte for byte with tests/expected/ordered.txt. The tests compare insert, erase, search and the in-order sequence against a reference model over random operations, check the level invariants and the size after every batch, cover duplicates and deletions on every level, and verify both experiments’ exact output. The workflows also run the tests and pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer, and the dangling-pointer and off-by-one pitfalls must produce their sanitizer summaries. Nothing is timed, because the experiments report counts.
What I Verified
The example directories contain the test programs and the captured runs. The table states which system ran each check.
| Check | Ubuntu 24.04 (WSL2) | Windows 11 (MSVC) |
|---|---|---|
| Build and tests, C, GCC 13.3, C11 and C17 | Pass (5 of 5 tests) | Not applicable |
| Build and tests, C, Clang 18.1.3, C11 and C17 | Pass (5 of 5 tests) | Not applicable |
Build and tests, C, MSVC 19.44 /W4 /WX | Not applicable | Pass (5 of 5 tests) |
| Build and tests, C++, g++ 13.3, C++17 and C++20 | Pass (6 of 6 tests) | Not applicable |
| Build and tests, C++, clang++ 18.1.3, C++17 and C++20 | Pass (6 of 6 tests) | Not applicable |
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive- | Not applicable | Pass (6 of 6 tests, C++17 and C++20) |
| AddressSanitizer and UndefinedBehaviorSanitizer, tests, demo and pitfalls | Pass (C 5 of 5, C++ 6 of 6) | Not applicable |
| Five pitfalls, each caught by its check or sanitizer summary | Pass (3 output checks, 2 AddressSanitizer summaries) | Not applicable |
| Level and lookup experiments, C and C++ | Run, identical tables, output above | Not run |
| Independent rerun on a second Linux x86-64 machine (GCC 13.3, Clang 18.1.3) | Pass (C 5 of 5, C++ 6 of 6 with both compilers, C under ASan and UBSan 5 of 5, demo, both experiments and all five pitfalls identical to the captures) | Not applicable |
Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, other promotion probabilities, concurrent or lock-free variants, and seeds other than the one above.




