Linked List Random Node
Given the head of a singly linked list, design a data structure that returns the value of a random node, where each node is equally likely to be chosen. Support this even without knowing the list length in advance (follow-up: constant extra space).
Open official problem prompt ↗Return a uniformly random node value from a linked list using only constant extra memory, even if the length is unknown.
A talent scout interviewing candidates one at a time who can only remember one favorite; each new candidate has a fair chance of becoming the new favorite so that everyone ends up equally likely.
- Input
- init([1,2,3]); getRandom()
- Output
- 2
- Why
- getRandom returns any of 1, 2, or 3 each with probability 1/3; 2 is one valid uniformly-random result.
The number of nodes in the list is between 1 and 10^4-10^4 <= Node.val <= 10^4At most 10^4 calls will be made to getRandom