Question

Formatted question description: https://leetcode.ca/all/382.html

 382	Linked List Random Node

 Given a singly linked list, return a random node's value from the linked list.
 Each node must have the same probability of being chosen.

 Follow up:
 What if the linked list is extremely large and its length is unknown to you?
 Could you solve this efficiently without using extra space?

 Example:

 // Init a singly linked list [1,2,3].
 ListNode head = new ListNode(1);
 head.next = new ListNode(2);
 head.next.next = new ListNode(3);
 Solution solution = new Solution(head);

 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
 solution.getRandom();

Algorithm

The most straightforward method is to first count the length of the linked list, and then randomly generate a position based on the length, and then traverse to this position from the beginning.

In Follow up, it is said that the linked list may be very long, and we cannot know the length in advance. Here we use the famous Reservoir Sampling idea.

Since head must exist, first let the return value res be equal to the node value of head, then let cur point to the next node of head, define a variable i, initialize it to 2.

  • If cur is not empty, start the loop, take a random number in [0, i-1],
  • If 0 is taken out, then res is updated to the current node value of cur, and then i is incremented by one and cur points to its next position. This is actually equivalent to maintaining a pond of size 1.
  • Then if the random number is generated as 0, exchange the value in the pond and the value currently traversed to ensure that the probability of each number is equal.

Code

Java

import java.util.Random;

public class Linked_List_Random_Node {
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {

        ListNode h = null;

        /**
         * @param head The linked list's head.
         *             Note that the head is guaranteed to be not null, so it contains at least one node.
         */
        public Solution(ListNode head) {
            this.h = head;
        }

        /**
         * Returns a random node's value.
         */
        public int getRandom() {
            Random rd = new Random();
            int ans = -1;
            int idx = 0;
            ListNode p = h;
            while (p != null) {
                idx++;
                int rn = rd.nextInt(idx);
                if (rn == idx - 1) {
                    ans = p.val;
                }
                p = p.next;
            }
            return ans;
        }
    }

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */
}

All Problems

All Solutions