Sponsored
Sponsored
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.
Time Complexity: O(N) for preprocessing, O(1) for getRandom
.
Space Complexity: O(N) for storing the list in an array.
1class ListNode {
2 constructor(val) {
3 this.val = val;
4 this.next = null;
5 }
6}
7
8class Solution {
9 constructor(head) {
10 this.values = [];
11 let node = head;
12 while (node !== null) {
13 this.values.push(node.val);
14 node = node.next;
15 }
16 }
17
18 getRandom() {
19 const randomIndex = Math.floor(Math.random() * this.values.length);
20 return this.values[randomIndex];
21 }
22}
In JavaScript, this approach involves storing the node values in an array. The getRandom
function then selects a random index using Math.random()
and returns the corresponding array element, ensuring equal selection probability.
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.
Time Complexity: O(N) for getRandom
.
Space Complexity: O(1).
1
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
public class Solution {
private ListNode head;
private Random rand;
public Solution(ListNode head) {
this.head = head;
this.rand = new Random();
}
public int GetRandom() {
ListNode node = head;
int reservoir = node.val;
int count = 1;
while (node != null) {
if (rand.Next(count) == 0) {
reservoir = node.val;
}
node = node.next;
count++;
}
return reservoir;
}
}
In the C# solution, reservoir sampling is implemented to keep track of one node's value while iterating through the linked list. The strategy grants each node an equal selection probability by adjusting the sampling probability dynamically.