Leetcode 382. Linked List Random Node
- Type: Linklist, random
- Approach:
- Using Reservoir Sampling method to solve the problem.
- For a linklist with n elements, we have 1/m possibility to choose the mth element, and (1-m)/m possibility not to choose it. Thus, for each element, it is be choosen by a possibility of 1/n.
- Proven: p(m) = 1/m x (m/(m+1) x (m+1)/(m+2) x ... x (n-2)/(n-1) x (n-1)/n) = 1/n.
- Complexity:
- Time: O(n)
- Space: O(1)