#382

Linked List Random Node

specialist · 660 · lc medium +30 · 64.7% accepted · 3,211 likes · top 68%

play →

Description

Build a structure around a singly linked list that can return a uniformly random node value on demand, with every node equally likely to be selected.

Implement the Solution class:

- Solution(ListNode head) Wraps the linked list starting at head.

- int getRandom() Picks a node at random and returns its value, each node equally likely.

Example 1:

Input
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 3, 2, 2, 3]

Example 2:

Explanation
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17