0
Leetcode Problem 382. Linked List Random Node
382. Linked List Random Node
AI Mock Interview
Leetcode Solutions
Reservoir Sampling
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Initialize a variable
chosen_value
to store the value of the randomly chosen node.
Initialize a variable
count
to keep track of the number of nodes seen so far.
Traverse the linked list starting from the head.
For each node encountered, increment
count
.
Generate a random number between 1 and
count
(inclusive).
If the random number is 1, update
chosen_value
with the current node's value.
Continue traversing until the end of the list.
Return
chosen_value
.
Fixed-Range Sampling
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...