382. Linked List Random Node (Medium)


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?


// 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.


class Solution {

    // To calculate the probability of a particular node, the idea is as follows.
    // Cursor start from head to tail of the list. Particular node happens to be chose
    // when the cursor moves to it, meanwhile the subsequent nodes are not chosen during traverse.

    // for node n-2, the probability of being chosen is (1/(n-2)) * ((n-2)/(n-1)) * ((n-1)/n) = 1/n
    // for node n-1, the probability of being chosen is (1/(n-1)) * ((n-1)/n) = 1/n
    // for node n, the probability of being chosen is 1/n

    ListNode head;
    Random random;

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

    public int getRandom() {
        ListNode cur = head;
        ListNode ans = head;

        for (int i = 1; cur != null; i++) {
            if (random.nextInt(i) == 0) {
                ans = cur;

            cur = cur.next;

        return ans.val;

Incorrect Solutions


Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-03-22 01:33:15

results matching ""

    No results matching ""