Linked List Random Node - Problem
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 listhead.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.
Input & Output
Example 1 — Basic Linked List
$
Input:
head = [1,2,3]
›
Output:
1 (or 2 or 3)
💡 Note:
Each call to getRandom() should return one of the values {1, 2, 3} with equal probability 1/3
Example 2 — Single Node
$
Input:
head = [5]
›
Output:
5
💡 Note:
Only one node exists, so getRandom() always returns 5 with probability 1
Example 3 — Larger List
$
Input:
head = [10,20,30,40,50]
›
Output:
30 (or any value from list)
💡 Note:
Each value has equal 1/5 probability of being selected
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
Visualization
Tap to expand
Understanding the Visualization
1
Input
Singly linked list with unknown length
2
Process
Apply reservoir sampling or two-pass selection
3
Output
Return random node value with uniform distribution
Key Takeaway
🎯 Key Insight: Reservoir sampling achieves uniform random selection in one pass without knowing list size
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code