Efficiently selecting a set of random elements from a linked list
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Introduction
If you need k uniformly random elements from a linked list and you do not know the list length in advance, reservoir sampling is the standard solution. It uses one pass, needs only O(k) extra space, and gives every element the same probability of being selected.
Why Linked Lists Change The Problem
With an array, you can often generate random indices directly. A linked list does not support efficient random access, so repeatedly choosing a random position and traversing to it would be expensive.
The constraints of a linked list are:
- access is sequential, not indexed
- length may be unknown
- the list may be streamed or too large to copy first
That is exactly the setting reservoir sampling was designed for.
Reservoir Sampling For k Items
The algorithm works like this:
- put the first
klist elements into a reservoir - for the
i-th later element, generate a random integer from0toi - if that random integer is less than
k, replace that reservoir entry - continue to the end of the list
At the end, every node has equal probability of being in the sample.
Python Example
Here is a runnable linked-list implementation with reservoir sampling.
This performs one traversal and never needs to index into the list itself.
Why It Is Uniform
The algorithm is elegant because it preserves uniform probability at every step.
- the first
kelements enter the reservoir immediately - later elements have a shrinking chance of replacing earlier entries
- the probabilities balance so that, after processing
nitems, each item has probabilityk / nof remaining in the reservoir
That is why reservoir sampling is preferred over ad hoc tricks such as random replacement with poorly chosen probabilities.
If You Need Only One Random Node
There is an even simpler special case when k = 1.
This single-item version is often asked in interviews because it captures the core idea with minimal code.
When A Two-Pass Solution Is Acceptable
If the list length is cheap to compute and memory is not a concern, you can also do:
- traverse once to count nodes
- choose random indices
- traverse again to collect them
That can be reasonable in controlled code, but it is worse than reservoir sampling when:
- the list is very large
- the data is streaming
- only one pass is available
- simplicity of a uniform one-pass algorithm matters
Reservoir sampling remains the most general answer.
Common Pitfalls
A common mistake is selecting random nodes with replacement and assuming the result is the same as sampling k distinct elements. It is not. That can produce duplicates unless you add extra bookkeeping.
Another issue is converting the entire linked list into an array first without considering memory or pass constraints. That may be acceptable in some applications, but it changes the problem and loses the main advantage of the streaming algorithm.
Be careful with off-by-one errors in the random range as well. The probability proof depends on the indexing logic being correct.
Finally, decide what should happen when k is larger than the list length. Many practical implementations return all elements in that case, which is what the code above effectively does.
Summary
- Reservoir sampling is the standard efficient solution for selecting random elements from a linked list.
- It uses one pass and
O(k)extra space. - Every element has equal probability of being selected.
- The
k = 1case is a particularly simple and common variant. - Avoid array conversion or repeated traversal unless the problem constraints genuinely allow it.
Related reading
- Efficiently sorting a numpy array in descending order?
- Election Algorithms - A ring algorithm
- Elegant Python code for Integer Partitioning
- Elegant way to find closest value in a vector from above
- Ehcache - using a ListInteger as the cache value
- Element-wise addition of 2 lists?
- Elegant/Clean special case Straight-line Grid Traversal Algorithm?
- Eliminating cyclic flows from a graph

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.