Skip to main content

Linked List Random Node - Solution & Explanation

MediumLinked ListMathReservoir SamplingRandomized14 min readAsked at: Meta, NVIDIA, Google
Practice this problem

Problem Statement

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

Implement the Solution class:

  • Solution(ListNode head) Initializes the object with the head of the singly-linked list head.
  • int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.

 

Example 1:

Input
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 3, 2, 2, 3]

Explanation
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.

 

Constraints:

  • The number of nodes in the linked list will be in the range [1, 104].
  • -104 <= Node.val <= 104
  • At most 104 calls will be made to getRandom.

 

Follow up:

  • What if the linked list is extremely large and its length is unknown to you?
  • Could you solve this efficiently without using extra space?

Approach Overview

Problem Overview: You receive the head of a singly linked list and must implement getRandom() so that every node value has the same probability of being returned. The challenge is that the list length may be unknown, and the structure only allows sequential traversal.

Approach 1: Preprocessing with Array (Time: O(1) per query, Space: O(n))

Traverse the linked list once during initialization and copy every node value into an array. When getRandom() is called, generate a random index between 0 and n-1 and return the value at that position. Array indexing is constant time, so each query is extremely fast. The trade‑off is memory usage: storing all node values requires O(n) extra space.

This approach works well when the list size is moderate and getRandom() is called many times. The one‑time preprocessing cost amortizes nicely across repeated queries.

Approach 2: Reservoir Sampling (Time: O(n) per query, Space: O(1))

When extra memory is restricted or the list length is unknown, use reservoir sampling. Iterate through the list while maintaining a candidate result. For the first node, select it as the current answer. For each subsequent node at position i, replace the stored value with probability 1/i. This probability rule guarantees that every node has equal probability of being chosen after the traversal finishes.

The algorithm works because each element survives the replacement process with equal likelihood. Only one variable stores the current candidate, so space remains constant. This method belongs to the family of randomized algorithms designed for streaming or unknown‑size data.

Recommended for interviews: Reservoir Sampling. Interviewers typically expect this solution because it demonstrates understanding of probability and algorithms for streaming data. The array preprocessing approach shows practical thinking, but the reservoir technique proves you know how to maintain uniform randomness without storing the entire dataset.

Approach 1: Approach 1: Preprocessing with Array

This method involves converting the linked list into an array during the initialization of the Solution object. Once the linked list is stored as an array, we can easily obtain a random node's value by selecting a random index in the array. This guarantees each node has an equal probability of being chosen.

In this solution, we first traverse the linked list to determine its size. We then allocate an array to hold all node values. A second traversal fills the array with the linked list's values. The getRandom function simply selects a random index from the array using the rand() function.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(N) for preprocessing, O(1) for getRandom.
Space Complexity: O(N) for storing the list in an array.

Try this approach in the editor →

Approach 2: Approach 2: Reservoir Sampling

Reservoir Sampling is an efficient algorithm that allows you to randomly select a single item from a stream (or a linked list) of unknown length with all items having an equal probability. You can accomplish this by traversing the linked list node by node, replacing the selected item with decreasing probability.

This C solution applies reservoir sampling to randomly select a node from the linked list. For each node, with probability 1/count, the current node value is chosen as the reservoir value, allowing us to accomplish this in one pass with constant space.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(N) for getRandom.
Space Complexity: O(1).

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Preprocessing with Array

Time Complexity: O(N) for preprocessing, O(1) for getRandom.
Space Complexity: O(N) for storing the list in an array.

Approach 2: Reservoir Sampling

Time Complexity: O(N) for getRandom.
Space Complexity: O(1).

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Preprocessing with ArrayO(n) preprocessing, O(1) per getRandom()O(n)When memory is available and getRandom() will be called many times
Reservoir SamplingO(n) per getRandom()O(1)When list size is unknown or memory is constrained

Video Solution

Linked List Random Node - (Leetcode - 382) - (GOOGLE) : Explanation ➕ Live Coding • codestorywithMIK • 16,137 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Linked List Random Node easy or hard?
Linked List Random Node is rated Medium difficulty on LeetCode. The traversal itself is simple, but recognizing and correctly implementing reservoir sampling requires understanding of probability and randomized algorithms.
How to solve Linked List Random Node in O(n)?
Use reservoir sampling while iterating through the linked list. Keep the current node as the answer with probability 1/i where i is the index of the node during traversal. After reaching the end, the stored value is guaranteed to be uniformly random across all nodes.
What is the best approach for Linked List Random Node?
Reservoir Sampling is the optimal interview approach. It scans the linked list once and selects each node with probability 1/n without storing the entire list. The algorithm runs in O(n) time per call and uses O(1) extra space.
Is Linked List Random Node asked at Google/Amazon/Meta?
This problem represents a classic reservoir sampling interview concept and has appeared in interviews at companies like Google, Amazon, and Meta. It tests understanding of probability, streaming algorithms, and linked list traversal.
What data structure is used in Linked List Random Node?
The core structure is a singly linked list. The optimized solution also relies on the reservoir sampling technique from randomized algorithms, while an alternative implementation stores node values in an array for constant-time random access.
What is the time complexity of Linked List Random Node?
The reservoir sampling solution runs in O(n) time for each getRandom() call because it traverses the linked list once. The preprocessing array approach requires O(n) time initially but answers each random query in O(1) time afterward.
Linked List Random Node Python or Java solution approach?
In Python or Java, iterate through the linked list while counting nodes and randomly replacing the current answer with probability 1/i. This implements reservoir sampling and guarantees uniform probability using only constant extra memory.

Ready to solve this problem?

Practice Linked List Random Node with our built-in code editor and test cases.

Practice on FleetCode