Mathematics matters in skip lists because a simple ordered linked list is easy to update but slow to search. A balanced tree searches quickly but maintains structural rules after every change. A skip list takes a third route: it builds several increasingly sparse express lanes above the base list and uses random heights so that long search paths are unlikely. Probability becomes an organising tool.
For students asking why mathematics is important in algorithms, skip lists connect geometric distributions, logarithms, expected value, invariants and experimental evidence. They also teach a mature lesson: “expected fast” and “worst-case fast” are different promises. A good engineer knows which one is being made, why it is reasonable and when a stronger guarantee is needed.
Quick Reading Routes
- Students can begin with the layered-list picture, trace a search and simulate node heights with coin flips.
- Parents and teachers can use the express-train analogy and the classroom card activity.
- Computing learners can focus on expected height, search paths, insertion, deletion and probabilistic guarantees.
- Practitioners can review memory overhead, concurrency, range scans, deterministic alternatives and benchmarking.
The Ordered-Set Problem
An ordered set or map supports operations such as search for a key, insert a key-value pair, delete a key and iterate through a key range. The data structure should preserve sorted order while keeping these operations efficient.
A sorted array
Binary search finds a key in logarithmic time, but inserting near the front may shift many elements. Arrays provide excellent locality and compact storage, which can outweigh update cost for read-heavy or batched workloads.
A sorted linked list
Once the insertion position is known, pointers can be changed locally. But finding that position may require walking node by node from the head, taking linear time.
A balanced search tree
Balanced trees maintain height near logarithmic through rotations, splits, merges or colour rules. They offer strong bounds but require more structural cases.
A skip list
A skip list keeps every key in a bottom sorted list. Some nodes are promoted to level 1, fewer to level 2, and so on. Search moves right while it can, then drops down when the next key would overshoot. The upper levels skip many bottom nodes.
The Original Idea
William Pugh introduced skip lists as a probabilistic alternative to balanced trees. The original paper explains their algorithms and analysis: Skip Lists: A Probabilistic Alternative to Balanced Trees. The ACM record is also available at doi:10.1145/78973.78977.
The key idea is not “be random and hope.” Each node’s height is drawn from a controlled distribution. The expected number of tall nodes falls geometrically, creating a hierarchy with predictable average shape.
A familiar picture
Imagine local train stops on level 0. Level 1 contains selected express stops. Level 2 contains a smaller set of super-express stops. A journey moves quickly along sparse lines, then changes down to denser lines near the destination.
Sentinels
Implementations often use a head sentinel with forward pointers at every active level and sometimes a tail sentinel. Sentinels remove special cases at the beginning or end, making the invariant easier to state.
Random Heights
Choose a promotion probability p, often 1/2 or 1/4. Every node has level 0. After creating a node, promote it to the next level with probability p; continue while promotion succeeds, up to a maximum level.
Height distribution
If height h means the node participates in levels 0 through h-1, then the probability of height at least k is p^(k-1). With p=1/2, half the nodes reach level 2, a quarter reach level 3, an eighth reach level 4 and so on in expectation.
Expected counts
With n=1,024 nodes and p=1/2, expected counts are about 1,024 at level 0, 512 at the next, 256 above that, then 128, 64 and so forth. Near level 10, only about one node is expected.
Expected maximum height
Solve n×p^(h-1)≈1. For p=1/2, h is about 1+log2 n. With 1,024 nodes, that is around 11 levels under this height convention. The actual maximum varies.
Memory overhead
A node of height h stores h forward pointers. The expected height is 1/(1-p). For p=1/2, expected pointers per node are 2. For p=1/4, they are 4/3. Lower p saves pointers but creates wider gaps and potentially more horizontal steps.
A Worked Search
Suppose the bottom level contains keys 3, 7, 12, 18, 25, 31, 44 and 50. Higher levels might be:
- Level 3: 12, 44
- Level 2: 7, 12, 31, 44
- Level 1: 3, 7, 12, 18, 31, 44, 50
- Level 0: every key
Search for 25. Start at the head on level 3. Move to 12 because 12<25. The next express key 44 overshoots, so drop. At level 2, 31 overshoots. Drop to level 1, move to 18, then drop to level 0 and move to 25.
Search invariant
At each step, the current node’s key is less than the target, and the next node at the current level is either less than the target or would overshoot. Moving right preserves order; moving down reveals a denser set without skipping a possible answer.
Failed search
Search for 26 follows a similar path, ending at 25 with next key 31. Because 26 lies strictly between them and level 0 contains every key, 26 is absent.
Predecessor queries
The final node before an overshoot is the predecessor. Skip lists naturally support lower-bound, upper-bound and range-start operations as well as exact lookup.
Why Expected Search Is Logarithmic
One analysis runs the search path backwards. At a node, moving up is possible when the node participates at the higher level; otherwise the reverse path moves left. With controlled promotion probability, the expected number of horizontal moves per level is constant, while the expected number of levels is logarithmic.
Intuition with p=1/2
Roughly half the nodes appear one level up. A search should cross only a small number of nodes before meeting a promoted one. There are about log2 n meaningful levels. Constant expected work per level times logarithmically many levels gives expected O(log n) search.
Expected is not absolute
A particular random construction can be unlucky. If no nodes are promoted, search degenerates to the bottom list and takes O(n). That outcome becomes extraordinarily unlikely for large n under a good random generator, but it is not logically impossible.
High-probability statements
Analysis can bound the probability that search greatly exceeds its expectation. A high-probability guarantee is stronger than an average over all random choices, yet still not the same as a deterministic worst-case bound.
Inputs do not choose heights
Random height generation separates structure from key insertion order. Sorted input that would ruin an ordinary unbalanced binary search tree does not automatically create a tall skip-list path, because promotion is independent of key value.
Insertion Step by Step
To insert key 27, search from the top and record the predecessor at each level in an update array. At level 0, the predecessor might be 25 and the successor 31.
Draw a random height for the new node. Suppose its height is 3. For levels 0, 1 and 2, redirect predecessor.forward[level] to the new node and set new.forward[level] to the old successor.
Why record predecessors
The search already discovers where the new node belongs at every level. Reusing those positions avoids a second traversal.
Sorted-order invariant
At every updated level, predecessor.key < 27 < successor.key. Pointer changes preserve increasing order. Untouched levels remain valid.
Duplicate policy
A map may replace the value for an existing key. A multiset may insert another record with a secondary tie-breaker. The policy must be explicit because equality changes search and iteration rules.
Maximum level
Implementations cap height to bound header size and pointer arrays. A cap somewhat above expected log base 1/p of maximum planned n is typical. Too low a cap turns top levels dense as the structure grows.
Deletion Step by Step
Search for the target and again record predecessors. If key 27 exists with height 3, then at each of its levels redirect the predecessor past it to its successor.
Shrinking the active height
If the highest levels become empty except for the head sentinel, reduce the current maximum level. The allocated cap can remain unchanged.
Memory reclamation
In single-threaded code, the deleted node can be freed after pointers are updated. In concurrent code, another reader may still hold a pointer. Safe reclamation methods such as epochs, hazards or reference schemes become essential.
Logical then physical deletion
Concurrent designs often mark a node logically deleted before unlinking it physically. This gives helpers and readers a stable way to interpret races, but proof obligations become much harder than the basic classroom algorithm.
Choosing the Promotion Probability
Promotion probability trades height, horizontal distance and memory.
p equals one half
Expected pointers per node are 2. Levels are relatively dense, so horizontal progress is quick. Height is about log2 n.
p equals one quarter
Expected pointers per node are 4/3, saving memory. Height is about log4 n, but the expected horizontal distance to a promoted node is larger.
A rough cost model
Let pointer memory cost be a, horizontal comparison cost b and vertical transition cost c. Expected cost can be modelled as a/(1-p)+b×H(p)+c×L(p), where H and L depend on workload and cache behaviour. The formula is a guide for measurement, not a universal optimum.
Hardware changes the answer
Pointer chasing can miss caches. A theoretically small comparison count may still be slower than a compact array structure. Benchmark on relevant key sizes, allocators and processors.
Range Queries and Ordered Iteration
Once a search reaches the first key in a range, iteration continues along level 0 in order. This is a major difference from an unordered hash table.
Example
To return keys from 18 through 44 inclusive, search for lower bound 18, then follow bottom pointers while key≤44. Work is expected O(log n+k), where k is the number of returned keys.
Pagination
Keyset pagination can resume from the last key rather than counting offsets. Stable ordering and unique tie-breakers prevent duplicates or omissions when items share the same primary sort value.
Snapshot questions
Concurrent updates may insert or delete while a range scan proceeds. Does the scan need a point-in-time snapshot, a weakly consistent view or merely memory safety? The answer changes implementation and semantics.
Skip Lists Versus Balanced Trees
Both can offer logarithmic search in common use, but the guarantees and layouts differ.
Structural maintenance
Balanced trees enforce invariants through rotations or node splits. Skip lists update forward pointers at a random number of levels. The code path can be conceptually simpler.
Worst case
A well-designed balanced tree provides deterministic logarithmic height. A basic random skip list has linear worst case, with good expected and high-probability behaviour.
Memory locality
Tree nodes and skip-list nodes are often heap allocated, causing pointer chasing. B-trees pack many keys per node and are strong for storage pages and caches. No data structure wins independently of hardware.
Concurrency
Skip lists can support fine-grained or lock-free update patterns because changes touch local forward pointers, though correct concurrent algorithms remain sophisticated. Trees also have mature concurrent forms.
Simplicity is contextual
A short sequential skip-list implementation is approachable. A production concurrent skip list with reclamation, duplicates and snapshots is not automatically simpler than a library tree.
Skip Lists Versus Hash Tables
Hash tables offer expected constant-time exact lookup under suitable assumptions, but do not naturally keep keys ordered.
Operations decide the choice
If an application needs only exact key lookup, a hash table may be better. If it needs predecessors, successors, sorted iteration or ranges, a skip list can support them directly.
Probability appears in both
Hash tables rely on key distribution, hash quality and resizing policy. Skip lists rely on height distribution. “Expected” performance is not unique to one structure.
Hybrid systems
Storage engines may use Bloom filters to avoid unnecessary lookups and ordered structures to locate ranges. Read Bloom filters, hash functions, false positives and memory efficiency for the set-membership side of that design.
Relationship to LSM Trees and Search Graphs
Skip lists often appear as in-memory ordered tables because inserts are local and iteration is sorted. An immutable sorted file can later be produced by walking level 0.
The article on LSM trees, compaction, write amplification and storage trade-offs explains the larger write-path context. A skip list can be one implementation choice for a mutable memory table; it is not the definition of an LSM tree.
Layered links also echo in HNSW graphs, approximate nearest neighbours, recall and search cost. HNSW is not a skip list for scalar keys, but its multi-layer navigation reflects a related intuition: sparse upper layers make long moves, dense lower layers refine the answer.
Randomness Quality and Reproducibility
Height generation needs a suitable source of pseudo-random bits. Cryptographic unpredictability is usually unnecessary, but severe bias or correlation can distort the level distribution.
Test the generator
Across many nodes, compare observed counts of height≥k with n×p^(k-1). Random variation is expected. A chi-square or confidence-interval check can reveal gross bias, though passing one test does not prove perfection.
Deterministic tests
Inject a seeded generator or a scripted height sequence. Tests can then create tall nodes, all-short nodes and boundary cases reproducibly.
Adversarial settings
If an attacker can predict or influence structural randomness, denial-of-service considerations may arise. Secret seeds, deterministic balancing or worst-case structures may be appropriate depending on threat model.
Randomness is part of the contract
Document whether performance is expected over internal random choices, input distribution or both. Those are different claims.
A Probability Calculation
With p=1/2, the probability that a node reaches height at least 10 is (1/2)^9=1/512 under the chosen convention. Among 10,240 nodes, the expected number reaching that height is 20.
The probability that at least one of n nodes reaches a very high level can be bounded with a union bound. If one node reaches height at least h with probability p^(h-1), then the chance that any of n nodes does is at most n×p^(h-1).
Example bound
For n=1,000,000, p=1/2 and h=31, the bound is 1,000,000/2^30≈0.000931. So a maximum height of 30 levels is exceeded with probability at most about 0.0931% under independent promotions. The bound may be loose but is easy to compute.
Why bounds help
An implementation chooses maximum level before seeing random outcomes. A probability bound turns “30 feels enough” into a quantified engineering risk for a planned size.
Concurrency and Linearisation
In a concurrent ordered map, an operation should appear to take effect at a well-defined point consistent with the specification.
Search races
A reader may see a node being inserted at one level but not another. Algorithms define ordering so partial visibility remains navigable and cannot produce an invalid key result.
Compare-and-swap
Lock-free variants may update pointers with atomic compare-and-swap. A failed CAS means another operation changed the expected link; the algorithm retries from a safe point.
Marked pointers
Deletion can mark links or nodes before unlinking. Readers help complete cleanup or skip marked nodes. Pointer bits, memory order and reclamation must be proven together.
Progress guarantees
Lock-free means the system as a whole continues under contention, not that every operation finishes quickly. Individual starvation remains possible. The lock-free queues article develops these progress and reclamation ideas in a queue setting.
Benchmarking a Skip List
Measure operations under a declared workload rather than quoting asymptotic notation alone.
Workload dimensions
- Number of keys and key-size distribution.
- Read, insert, delete and range-scan proportions.
- Uniform, sequential, clustered or adversarial access.
- Thread count and contention.
- Promotion probability and maximum level.
- Allocator, memory limits and hardware.
Metrics
Report throughput, median and tail latency, comparisons, pointer traversals, bytes per key, cache misses and allocation cost. Averages can hide rare long searches.
Baselines
Compare with a sorted vector for read-heavy data, a balanced tree for ordered updates and a hash table for exact lookup. Equal functionality matters: include range queries only for structures that support them or account for auxiliary indexes.
Confidence
Repeat with multiple random seeds. If results swing widely, seed sensitivity is itself an important finding.
Misconceptions Worth Correcting
“Random means unstructured”
The level distribution is carefully controlled. Random choices create a predictable aggregate shape.
“Expected O(log n) means every search is logarithmic”
No. It describes average behaviour over the data structure’s randomness. High-probability bounds add confidence but remain probabilistic.
“Skip lists are always faster than trees”
Cache layout, allocation, concurrency and operation mix decide real performance. Asymptotic class is only one dimension.
“More levels are always better”
Extra pointers consume memory and may add cache misses. Promotion probability balances vertical and horizontal work.
“A random seed does not matter”
It determines heights and can affect benchmark outcomes. Production randomness and test reproducibility both deserve attention.
Which Mathematics Matters Most?
Geometric probability describes node heights. Logarithms estimate the number of layers. Expected value predicts pointer counts and search work. Probability bounds quantify rare tall structures. Invariants prove sortedness. Algorithm analysis separates expected, amortised and worst-case claims. Statistics validates implementation behaviour.
This mixture is why skip lists are such a satisfying educational topic. No single equation builds the structure. Mathematics works as a collection of lenses: design the distribution, preserve order, estimate work, bound risk and test the real machine.
A Practical Learning Sequence
1. Build a sorted linked list and count steps for several searches. 2. Add one express level manually and trace successful and failed searches. 3. Generate heights by coin flips and build four levels. 4. Calculate expected node counts at each level. 5. Implement predecessor recording for insertion and deletion. 6. Run multiple seeds and plot search-length distributions. 7. Compare p=1/2 with p=1/4 for pointers, comparisons and time.
A paper activity
Write ordered keys on cards. Every card enters level 0. Flip a coin for each card; heads promotes it. Keep flipping for promoted cards. Arrange the promoted copies on higher rows. Learners search by moving right and down with a pencil.
Ask them to rebuild with a different seed. The exact towers change, but the sparse-layer pattern usually remains. That contrast makes “random instance, predictable distribution” visible.
A coding project
Implement a map with find, insert, delete and range. Inject a random-height function. Add a validator that checks sorted links at every level, every higher-level node also appears below, and no pointer skips backward.
Instrument horizontal and vertical moves. Report distributions across at least 30 seeds. Finally force every height to 1 and show the linear fallback; then force a scripted balanced pattern and compare.
Guidance for Students
Draw before coding. A pointer update is much easier to verify when predecessors and successors are visible on each level.
Use one height convention consistently. Some descriptions call the bottom level level 1; others call it level 0. Some say height is the number of levels, others the highest index. Off-by-one confusion can spoil correct probability formulas.
Label the kind of claim you make. Say “expected search time,” “observed median over 50 seeds” or “worst case,” not simply “fast.” Precise qualifiers are a strength, not a weakness.
Guidance for Parents and Teachers
Skip lists make probability constructive. Coin flips do not merely predict a game; they build a useful index. This can change a learner’s view of randomness from chaos to a controlled design resource.
Invite explanation at three levels: the story of express stops, the procedure of right-then-down search, and the probability of tall nodes. Moving between analogy, algorithm and formula develops flexible understanding.
Avoid making one unlucky classroom run look like failure. Repeat. The distribution is the lesson. Ask why a claim about expectation needs several trials.
Did You Know?
A skip list can be built from the bottom up with random towers, yet searched from the top down with deterministic comparisons. Randomness shapes the index; each individual lookup follows a clear rule.
Also, reducing promotion probability does not simply make the structure “shorter.” It reduces tower count and pointer memory while increasing gaps between express nodes. The interesting quantity is total work, not height alone.
A Complete Insert-and-Delete Trace
Start with keys 10, 20, 30, 40 and 50. Suppose their heights are 1, 3, 1, 2 and 1. The head sentinel reaches three active levels.
At level 2, the path contains head→20. At level 1, it contains head→20→40. At level 0, it contains every key.
Insert key 35 with height 3
Search begins at level 2. Move to 20; the next pointer is the tail, which overshoots. Record 20 as the predecessor at level 2 and drop. At level 1, the next key is 40, so record 20 again. At level 0, move from 20 to 30, then record 30.
Set new.forward[0]=40 and 30.forward[0]=35. Set new.forward[1]=40 and 20.forward[1]=35. Set new.forward[2]=tail and 20.forward[2]=35. Sorted order holds at all three levels.
Search for 37
At level 2, move to 20 then 35. The next node overshoots, so drop. No further right move is possible at level 1. At level 0, next is 40. Because 37 lies between 35 and 40, it is absent. Notice how the tall new node becomes the predecessor for nearby searches.
Delete key 20
Search records the head as predecessor at levels 2 and 1, and key 10 at level 0. At each level where predecessor.forward points to 20, redirect it to 20.forward. Level 2 now begins head→35; level 1 begins head→35→40; level 0 becomes 10→30→35→40→50.
Validate after mutation
Check that every level is strictly ordered, every level-i node also exists at all lower levels, the bottom contains exactly the map’s keys, and current height equals the highest non-empty level. A validator catches pointer errors earlier than a failed user query.
Rank, Span and Indexable Skip Lists
A basic skip list searches by key. Add a span to each forward pointer—the number of bottom-level nodes it crosses—and the structure can answer rank questions.
Select by rank
To find the 100th key, begin at the top with cumulative rank zero. Move right when adding the pointer’s span does not pass 100; otherwise drop down. This mirrors key search but compares accumulated counts.
Insert updates spans
Insertion splits spans around the new node. If a pointer previously crossed seven bottom nodes and the new node lies three positions after its predecessor, the predecessor-to-new span becomes three and new-to-successor gets the remainder under the implementation’s counting convention.
Applications
Rank support enables percentile selection, leaderboard position and pagination by ordinal. It costs extra metadata and more complex updates. Again, added capability changes constants and proof obligations.
Weighted spans
Spans can store cumulative weights rather than counts, supporting selection by total weight. Floating-point accumulation or mutable weights introduce additional accuracy and update questions.
Deterministic and Quasi-Random Variants
Randomised skip lists are not the only layered-list design.
Deterministic balancing
A deterministic skip list maintains gap constraints between promoted nodes. Updates may trigger promotions or demotions resembling tree rebalancing. It can provide worst-case guarantees while retaining layered navigation.
Quasi-random rebuilds
A structure can rebuild levels during a full traversal using controlled pseudo-random choices. This may hide exact promotion patterns from an adversary while amortising reconstruction.
Trade-off
Random independent towers give simple local insertion. Deterministic constraints give stronger worst-case shape but require maintenance. The right promise depends on threat model, latency objective and code complexity.
Do not mix proofs
An expected-time proof for independent geometric heights does not automatically apply after adaptive promotions. A deterministic gap invariant needs its own proof. Implementation and analysis must describe the same algorithm.
Memory Layout Improvements
Pointer-rich nodes can waste space and cache bandwidth.
Variable-sized towers
Allocate each node with exactly its height’s pointer slots. This saves memory but complicates allocation and alignment.
Separate tower storage
Keep base records compact and store upper-level links separately. Searches touch express metadata first, then fetch full records near the answer.
Arena allocation
An arena can place nodes closer together, reduce per-node allocator overhead and improve locality. Deletion becomes delayed or batch-based, which may fit immutable or epoch-managed workloads.
Compressed pointers
If an arena is smaller than the full address space, store offsets instead of machine-width pointers. Decoding costs arithmetic but can improve cache density.
Measure the whole effect
Saving bytes per node may add instructions. Benchmark both latency and memory across realistic sizes. A compact design often wins when the working set crosses a cache boundary.
Practice Problems With Solutions
Problem 1: Expected level counts
For n=4,096 and p=1/4, expected nodes with height at least 2 are 1,024; at least 3 are 256; at least 4 are 64; at least 5 are 16; at least 6 are 4; at least 7 are 1. The exact counts are random.
Problem 2: Expected pointer count
With p=1/4, expected height is 1/(1-p)=4/3. For one million nodes, expect about 1.333 million forward pointers before sentinels and allocation overhead.
Problem 3: Worst case
If every node has height 1, a search for the final key examines all n bottom nodes, so worst-case time is O(n). This does not contradict expected O(log n).
Problem 4: Lower bound
In keys [5,9,14,22], lower_bound(13) returns 14, while predecessor(13) returns 9. Define the API because “nearest” is ambiguous.
Problem 5: Promotion convention
If a node always has level 0 and is promoted with probability 1/2, P(height≥4)=1/8 when height counts total levels. If height means highest zero-based index, wording changes. Write the event explicitly to avoid off-by-one errors.
Problem 6: Range complexity
Expected search to the first result is O(log n). Returning k consecutive nodes costs O(k), so total is O(log n+k). No ordered structure can output k records in less than proportional output work.
FAQ
Can a skip list contain duplicate keys?
Yes, if the design defines a secondary order or stores multiple values per key. A map usually keeps unique keys. Search, deletion and range semantics must match the policy.
Why not use binary search on a linked list?
Binary search needs efficient access to the middle element. A linked list reaches the middle by walking, so repeated midpoint access loses the array advantage. Skip pointers create faster navigation paths.
Is a skip list balanced?
It is balanced probabilistically in aggregate, not by a strict tree-height invariant. Expected and high-probability path lengths are good under the model.
How large should maximum level be?
Choose it from expected maximum size, promotion probability and an acceptable overflow probability. Then test memory and workload. There is no universal constant.
Are skip lists suitable for disks?
Pointer-heavy layouts can perform poorly on storage compared with page-oriented B-trees. Variants exist, but storage block size and I/O locality must drive the decision.
What should a student remember?
Every key lives at the bottom. Random promotion builds sparse express lanes. Search moves right without overshooting, then down. Controlled geometric heights yield expected logarithmic work.
Useful Next Reading
- Read version control, commit graphs, hashes and merging for another graph-shaped navigation problem.
- Revisit the original skip-list paper and compare its probability convention with your implementation.
- Read the ACM record for publication details and the paper abstract.
Final Perspective
Skip lists show why mathematics matters in data structures. Logarithms explain how a tall hierarchy can cover many keys. Geometric probability decides how many towers reach each level. Invariants preserve sorted order while local pointers change. Experiments test whether expected behaviour survives real memory and concurrency.
The most useful lesson is optimistic: structure does not always require rigid central maintenance. Independent small random choices can create an efficient global pattern. When the promise is stated honestly—expected logarithmic performance, with measured constants and known worst case—the result is both elegant and practical.
