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 list head.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.Note:
getRandom()
?
getRandom()
should return a node value chosen randomly, with each node having an equal probability of being chosen.To solve this problem efficiently, we can use Reservoir Sampling algorithm, which allows us to randomly select an element from a list of unknown length where each element has an equal probability of being selected.
Steps to implement:
result
to None
.current
to the head and set index n = 1
.1/n
.result
with the current node’s value.n
.result
.Here’s the implementation of the problem using the described strategy:
import random
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def __init__(self, head: ListNode):
self.head = head
def getRandom(self) -> int:
# Initially, the result is the value at head
result, current, n = None, self.head, 1
while current:
# Use random to decide whether to update the result
if random.randint(1, n) == n:
result = current.val
current = current.next
n += 1
return result
__init__
method): O(1) because we’re only storing the reference to the head of the linked list.getRandom
method: O(N) where N is the number of nodes in the linked list, as we need to traverse the entire list to ensure each node has an equal probability of being selected.This approach guarantees each node has an equal chance of being returned due to the properties of the reservoir sampling algorithm.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?