Linked List Random Node

Problem

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();

Solution

public class Solution {

    Random random;
    ListNode head;

    public Solution(ListNode head) {
        this.head = head;
        this.random = new Random();
    }

    public ListNode getRandom() {
        ListNode cur = head;
        int res = cur.val;
        for (int i = 1; cur.next != null; i++) {
            cur = cur.next;
            if (random.nextInt(i + 1) == i) res = cur.val; //This makes th equal probability  
        }
        return res;
    } 
}

Analysis

We need to make sure each node has same chance to be returned
We first set the returned val as head.val and set cur = head
Then we loop through the second node till the end
If random.nextInt(i + 1) = i we change the returned val to cur.val
This is because when it reaches the second node, it has 1/2 probability to set res, and same as the first node
As the i grows, each node will have smaller but always same chance to set as res

results matching ""

    No results matching ""