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.
1import random
2
3class ListNode:
4 def __init__(self, x):
5 self.val = x
6 self.next = None
7
8class Solution:
9 def __init__(self, head: ListNode):
10 self.values = []
11 node = head
12 while node:
13 self.values.append(node.val)
14 node = node.next
15
16 def getRandom(self) -> int:
17 return random.choice(self.values)
In Python, this approach stores all the linked list values in a list during initialization. The getRandom
function uses Python's random.choice()
to return a value from the list, ensuring equal 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
This C solution applies reservoir sampling to randomly select a node from the linked list. For each node, with probability 1/count, the current node value is chosen as the reservoir value, allowing us to accomplish this in one pass with constant space.