Skip Lists and Indexing (DSA #19)
A sorted linked list answers a search in \(O(n)\): you walk every node. A balanced tree gets \(O(\log n)\) but needs rotations and careful code. A skip list gets the same \(O(\log n)\) expected time with nothing but linked lists and coin flips — no rotations, no rebalancing, and code simple enough to reason about under concurrency. It is the ordered structure behind Redis’s sorted sets and the in-memory tables of several storage engines.
The second half of this chapter connects these structures to indexing: how databases and file systems find a row without scanning the whole file.
The skip-list idea: express lanes
Start with a sorted linked list. Add a second list that skips every other node, a third that skips every fourth, and so on. A search starts on the sparsest lane, moving right until the next node would overshoot, then drops down a lane. It covers ground quickly on the top lanes and fine-tunes at the bottom.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, minimum width=0.62cm, minimum height=0.55cm, font=\small\bfseries},
a/.style={->, thick}]
\foreach \v [count=\i from 0] in {1,2,3,4,5,6,7,8} {
\node[n, fill=blue!8] (b\i) at (\i*0.8,0) {\v};
}
\foreach \i in {0,2,4,6} { \node[n, fill=green!20] (m\i) at (\i*0.8,0.85) {\the\numexpr\i+1}; }
\foreach \i in {0,4} { \node[n, fill=orange!25] (t\i) at (\i*0.8,1.7) {\the\numexpr\i+1}; }
\draw[a] (t0) -- (t4);
\draw[a] (m0) -- (m2); \draw[a] (m2) -- (m4); \draw[a] (m4) -- (m6);
\draw[a] (b0) -- (b1); \draw[a] (b1) -- (b2); \draw[a] (b2) -- (b3);
\draw[a] (b3) -- (b4); \draw[a] (b4) -- (b5); \draw[a] (b5) -- (b6); \draw[a] (b6) -- (b7);
\draw[->, very thick, red!70!black] (t0.south) -- (m0.north);
\draw[->, very thick, red!70!black] (m2.south) -- (b2.north);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (3.2,-0.6) {drop down when the next node overshoots};
\end{tikzpicture}
The levels are assigned randomly: each node is promoted to the next level with probability \(1/2\). Expected height is \(O(\log n)\), and expected search cost is \(O(\log n)\) — the same as a balanced tree, in expectation.
import random
class SkipNode:
def __init__(self, val, level):
self.val = val
self.next = [None] * (level + 1) # one forward pointer per level
class SkipList:
def __init__(self, max_level=16, p=0.5):
self.head = SkipNode(float("-inf"), max_level)
self.max_level, self.p = max_level, p
Search
Start at the top-left; move right while the next value is smaller than the target; otherwise drop a level.
def search(self, target):
node = self.head
for level in range(self.max_level, -1, -1):
while node.next[level] and node.next[level].val < target:
node = node.next[level]
node = node.next[0] # candidate at the base lane
return node if node and node.val == target else None
Each lane lets you skip more nodes than the lane below, so the expected number of steps is \(O(\log n)\).
Insert and delete
Insert finds the position on every level, then links the new node into the lanes up to its randomly chosen height. Delete is the reverse: find the predecessors on each level and skip the node.
def insert(self, val):
update = [None] * (self.max_level + 1)
node = self.head
for level in range(self.max_level, -1, -1):
while node.next[level] and node.next[level].val < val:
node = node.next[level]
update[level] = node
level = self._random_level()
new = SkipNode(val, level)
for i in range(level + 1):
new.next[i] = update[i].next[i]
update[i].next[i] = new
def _random_level(self):
level = 0
while random.random() < self.p and level < self.max_level:
level += 1
return level
No rotations, no height bookkeeping — this is why skip lists are popular where lock-free or concurrent structures are needed (Redis, Java’s ConcurrentSkipListMap).
Skip list vs balanced tree
| Skip list | Balanced BST | |
|---|---|---|
| Expected search | \(O(\log n)\) | \(O(\log n)\) worst case |
| Worst case | \(O(n)\) (unlikely) | \(O(\log n)\) guaranteed |
| Implementation | simple | rotations |
| Concurrency | easy | harder |
| Range scan | walk the base lane | inorder traversal |
The trade is a probabilistic guarantee for simpler code and better concurrency behaviour. The probability of a bad level assignment is vanishingly small, and a randomized structure cannot be forced into its worst case by adversarial input order the way a deterministic BST can.
Indexing: finding rows without scanning
An index is an auxiliary structure that maps key values to locations, so a query can jump instead of scanning. Three families:
Linear (sequential) indexing. Keep a sorted file by key; search is binary search over the file, \(O(\log n)\) seeks but each seek reads a page. Simple, good for batch processing, poor for random point lookups.
Tree-based indexing. A B+ tree (Chapter 13) maps keys to row locations. Internal nodes route, leaves hold pointers, and the tree stays short so few disk pages are read. This is the default index in PostgreSQL, MySQL/InnoDB, and most relational databases.
# conceptual: an index is just an ordered map key -> row location
index = {} # in memory: a hash/tree map
# on disk: a B+ tree with leaf pointers into the heap file
Hash indexing. A hash table (Chapter 6) maps keys directly to locations, giving \(O(1)\) point lookups but no range scans or ordering. Databases use hash indexes only when equality queries dominate.
| Index | Point lookup | Range scan | Order |
|---|---|---|---|
| Linear | \(O(\log n)\) + seeks | good (sequential) | yes |
| B+ tree | \(O(\log_m n)\) | excellent (linked leaves) | yes |
| Hash | \(O(1)\) avg | impossible | no |
ISAM (Indexed Sequential Access Method)
ISAM is the classic bridge between sequential and indexed access: a sorted data file plus a sparse index of the first key of each block. Look up the block via the index, then scan within it. It is an early ancestor of the B+ tree, still found in some mainframe and legacy systems.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum width=2.1cm, minimum height=0.6cm, font=\small},
a/.style={->, thick}]
\node[b, fill=orange!22] (idx) at (0,0) {index: A, F, M, T};
\node[b, fill=blue!12] (b1) at (-2.6,-1.0) {block A...E};
\node[b, fill=blue!12] (b2) at (0,-1.0) {block F...L};
\node[b, fill=blue!12] (b3) at (2.6,-1.0) {block M...S};
\draw[a] (idx) -- (b1); \draw[a] (idx) -- (b2); \draw[a] (idx) -- (b3);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.5) {index points to blocks; scan the chosen block};
\end{tikzpicture}
The design lesson: indexes trade write cost and space for read speed. Every index must be updated on every insert/delete, so more indexes mean slower writes. Choosing indexes is balancing read paths against write paths.
Pitfalls
- Assuming worst-case \(O(\log n)\) for a skip list. It is expected; an unlucky random assignment can be worse, though astronomically unlikely.
- Wrong promotion probability. \(p = 1/2\) balances height and steps; extreme \(p\) values degrade performance.
- Unbounded levels. Cap the maximum level at about \(\log_{1/p} n\) to bound memory.
- Indexing everything. Each index slows writes and consumes space; index the queries you actually run.
- Hash index for range queries. A hash index cannot serve
BETWEENorORDER BY; use a B-tree. - Expecting ISAM to stay balanced. Classic ISAM does not rebalance like a B+ tree; long-term growth degrades it.
How does a skip list achieve expected \(O(\log n)\) without rotations? When would you choose a hash index over a B+ tree index?
ASolution
Randomly promoted nodes create express lanes; a search moves right on sparse lanes and drops down, skipping large chunks, for expected \(O(\log n)\). Choose a hash index when queries are equality-only and you want \(O(1)\) lookups; choose a B+ tree when you need range scans or ordered results.
Next: Graph Data Structures (DSA #20) — nodes, edges, and the two fundamental traversals.