Skip to content
Problem 382 · LeetCode 382(opens in a new tab)

Linked List Random Node

MediumLinked lists

Build a class Solution whose constructor receives the head of a singly linked list. Its method getRandom() returns the value of one node of that list, chosen at random.

Every node must be equally likely to be picked on every call. If a value appears in several nodes, it comes back more often, in proportion to how many nodes hold it.

Example 1

Input:  Solution(4 → 7 → 2), then getRandom() four times
Output: four values, each one of 4, 7, 2, e.g. 7, 2, 2, 4
Why:    each node has chance 1/3 on every call
2 more examples and the constraints

Example 2

Input:  Solution(9), then getRandom()
Output: 9
Why:    a single node is the only choice

Example 3

Input:  Solution(-3 → -3 → 8), then getRandom()
Output: -3 two times in three, 8 one time in three
Why:    two of the three nodes hold -3

Constraints

  • 1 ≤ number of nodes ≤ 10,000
  • −10,000 ≤ node value ≤ 10,000
  • getRandom is called at most 10,000 times

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Copy into an arrayO(1) per call
  2. Reservoir samplingO(n) per call

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeExtra memory for 10,000 nodesVerdict
Copy into an arrayO(1) per call
Fast calls; copies every value
Reservoir samplingO(n) per call
Best on memory; answers the follow-up

n = number of nodes. The bars compare extra memory, not time.

Edge cases to test

  • One node. Its value must come back on every call; randrange(1) is always 0.
  • Repeated values. -3 → -3 → 8 returns -3 twice as often as 8: fairness is per node, not per value.
  • Values at the limits. 10,000 and −10,000 are just values; no arithmetic is done on them.
  • Many calls on a long list. 10,000 calls on 10,000 nodes is 100 million steps for reservoir sampling; the array answers each in O(1).

Common mistakes

  • Replacing the choice with probability 1/2 at every node, which heavily favours the last nodes.
  • Rolling randrange(count + 1) or starting count at 0 when rolling, which skews the odds or divides by zero.
  • Returning the node itself instead of its value, or caching one pick and returning it on every call.

How to talk through it

  1. 1Clarify. Is the list fixed after construction? How many calls? Is memory tight, or the length unknown?
  2. 2Give the array copy. Copy once, then pick a random index: O(1) per call, O(n) memory.
  3. 3Answer the follow-up. Reservoir sampling: keep the k-th node with chance 1/k, one pass per call.
  4. 4Prove it is fair. Chosen at k, then kept by every later node: the product is 1/n for each node.
  5. 5Test out loud. Run a one-node list and a list where every node holds the same value.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?