Linked List Random Node

medium linked list reservoir sampling

Problem

Return a uniformly random node value from a linked list of unknown length using O(1) extra memory.

Inputhead = 1 → 2 → 3 → 4 → 5
Outputany of {1, 2, 3, 4, 5} with prob 1/5
Walk once; at node i (1-indexed), replace the answer with this value with probability 1/i.

import random

class Solution:
    def __init__(self, head):
        self.head = head
    def getRandom(self):
        ans, i = self.head.val, 1
        node = self.head.next
        while node:
            i += 1
            if random.randint(1, i) == 1:
                ans = node.val
            node = node.next
        return ans
class Solution {
  constructor(head) { this.head = head; }
  getRandom() {
    let ans = this.head.val, i = 1;
    for (let node = this.head.next; node; node = node.next) {
      i++;
      if (Math.floor(Math.random() * i) === 0) ans = node.val;
    }
    return ans;
  }
}
class Solution {
    private ListNode head;
    private Random rng = new Random();
    public Solution(ListNode head) { this.head = head; }
    public int getRandom() {
        int ans = head.val, i = 1;
        for (ListNode node = head.next; node != null; node = node.next) {
            i++;
            if (rng.nextInt(i) == 0) ans = node.val;
        }
        return ans;
    }
}
class Solution {
    ListNode* head;
public:
    Solution(ListNode* head) : head(head) {}
    int getRandom() {
        int ans = head->val, i = 1;
        for (ListNode* n = head->next; n; n = n->next) {
            i++;
            if (rand() % i == 0) ans = n->val;
        }
        return ans;
    }
};
Time: O(n) per call Space: O(1)