Algo-Sim › Math & Geometry

Linked List Random Node

Medium · Math & Geometry · step through it in Java, Python and C++ on your own input

Return a uniformly random node value in one pass with O(1) space: reservoir sampling keeps the i-th node with probability 1/i.

Problem

Given a singly linked list, implement getRandom(), which returns the value of a random node, every node equally likely. Follow-up: the list may be very long and its length unknown; can you do it without extra space?

Constraints

Edge cases to test

Follow-up questions

How do you pick k random nodes?
Reservoir sampling of size k: keep node i with probability k/i, replacing a random slot. O(n) time, O(k) space.
When would you store the values instead?
If the list is fixed and getRandom is called often, copy to an array once: O(1) per pick at O(n) memory.

Solution

Java

class Solution {
    private final ListNode head;
    private final Random rand = new Random();

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

    // Reservoir sampling: keep the i-th node with probability 1/i.
    public int getRandom() {
        int result = 0, i = 0;
        for (ListNode node = head; node != null; node = node.next) {
            i++;
            if (rand.nextInt(i) == 0) result = node.val;
        }
        return result;
    }
}

Python

import random


class Solution:
    def __init__(self, head):
        self.head = head

    # Reservoir sampling: keep the i-th node with probability 1/i.
    def getRandom(self):
        result, i, node = 0, 0, self.head
        while node:
            i += 1
            if random.randint(0, i - 1) == 0:
                result = node.val
            node = node.next
        return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
    ListNode *head;

  public:
    Solution(ListNode *head) : head(head) {}

    // Reservoir sampling: keep the i-th node with probability 1/i.
    int getRandom() {
        int result = 0, i = 0;
        for (ListNode *node = head; node; node = node->next) {
            i++;
            if (rand() % i == 0) result = node->val;
        }
        return result;
    }
};

More Math & Geometry problems