bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 382. Linked List Random Node

382. Linked List Random Node

Leetcode Solutions

Reservoir Sampling

  1. Initialize a variable chosen_value to store the value of the randomly chosen node.
  2. Initialize a variable count to keep track of the number of nodes seen so far.
  3. Traverse the linked list starting from the head.
  4. For each node encountered, increment count.
  5. Generate a random number between 1 and count (inclusive).
  6. If the random number is 1, update chosen_value with the current node's value.
  7. Continue traversing until the end of the list.
  8. Return chosen_value.
UML Thumbnail

Fixed-Range Sampling

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...