Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

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.

Implement the Solution class:

Naive Solution

Reservoir Sampling Solution

Code

class Solution {
private:
    ListNode* root;

public:
    Solution(ListNode* head){
        this->root = head;
    }

    int getRandom()
    {
        ListNode* curr = root;
        int ans = 0, x = 1;
        while (curr) {
            if (rand() % x == 0) ans = curr->val;
            x++;
            curr = curr->next;
        }
        return ans;
    }
};