Algo-Sim › Math & Geometry
Linked List Random Node
Medium · Math & Geometry · step through it in Java, Python and C++ on your own input
Return a uniformly random node value in one pass with O(1) space: reservoir sampling keeps the i-th node with probability 1/i.
Problem
Given a singly linked list, implement getRandom(), which returns the value of a random node, every node equally likely. Follow-up: the list may be very long and its length unknown; can you do it without extra space?
Constraints
- 1 ≤ number of nodes ≤ 10⁴
- −10⁴ ≤ Node.val ≤ 10⁴
- At most 10⁴ calls to getRandom
- Here a seed fixes the random draws so runs repeat
Edge cases to test
- One node
- Duplicate values
- A very long list
Follow-up questions
- How do you pick k random nodes?
- Reservoir sampling of size k: keep node i with probability k/i, replacing a random slot. O(n) time, O(k) space.
- When would you store the values instead?
- If the list is fixed and
getRandomis called often, copy to an array once: O(1) per pick at O(n) memory.
Solution
Java
class Solution {
private final ListNode head;
private final Random rand = new Random();
public Solution(ListNode head) {
this.head = head;
}
// Reservoir sampling: keep the i-th node with probability 1/i.
public int getRandom() {
int result = 0, i = 0;
for (ListNode node = head; node != null; node = node.next) {
i++;
if (rand.nextInt(i) == 0) result = node.val;
}
return result;
}
}Python
import random
class Solution:
def __init__(self, head):
self.head = head
# Reservoir sampling: keep the i-th node with probability 1/i.
def getRandom(self):
result, i, node = 0, 0, self.head
while node:
i += 1
if random.randint(0, i - 1) == 0:
result = node.val
node = node.next
return resultC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
ListNode *head;
public:
Solution(ListNode *head) : head(head) {}
// Reservoir sampling: keep the i-th node with probability 1/i.
int getRandom() {
int result = 0, i = 0;
for (ListNode *node = head; node; node = node->next) {
i++;
if (rand() % i == 0) result = node->val;
}
return result;
}
};
More Math & Geometry problems
- Plus One (Easy)
- Happy Number (Easy)
- GCD and LCM (Euclid) (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Pow(x, n) (Medium)
- Count Good Numbers (mod 1e9+7) (Medium)
- Multiply Strings (Medium)
- Reverse Integer (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Random Pick with Weight (Medium)
- Shuffle an Array (Medium)
- Pascal's Triangle (Easy)
- nCr mod p (Medium)
- Max Points on a Line (Hard)