Linked List Random Node
Solution Code
import random
class Solution:
def __init__(self, head: ListNode):
self.head = head
def getRandom(self) -> int:
curr = self.head
chosen_val = curr.val
i = 1
while curr.next:
curr = curr.next
i += 1
if random.random() < 1 / i:
chosen_val = curr.val
return chosen_valTime Complexity
O(1) for getRandom
Space Complexity
O(N)

