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
Utilizing Python's random number generator, this solution efficiently picks a random node from the linked list using reservoir sampling, where each item maintains equal likelihood of being selected throughout.