Skip to content

Practice Linked List Random Node

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#382
LeetCode Problem

Linked List Random Node

Problem Statement

Solution(head) receives a nonempty singly linked list. getRandom() returns a node value, selecting each node with equal probability. Equal values in different nodes remain distinct sampling opportunities. Practice approach: Reservoir sampling uses O(1) extra space without needing the list length. During a traversal, replace the selected value at node i with probability 1/i. Each node then has final probability 1/n. A stored array of node values instead offers O(1) sampling after O(n) preprocessing and storage. Test repeated values and a single-node list.

Source: Linked List Random Node on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["Solution","getRandom","getRandom"]
[[[4,9,9]],[],[]]
Output
[null,9,4]
Explanation

This is one possible sample sequence. Value 9 has probability 2/3 because two of the three nodes contain it; 4 has probability 1/3.

Constraints

1 <= node count <= 10^4
-10^4 <= Node.val <= 10^4
At most 10^4 getRandom calls.

Related LeetCode Problems

Practice more problems similar to Linked List Random Node.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.