Leetcode 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:
Solution(ListNode head)
Initializes the object with the head of the singly-linked list head
.int getRandom()
Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.i-th
node, select it with probability 1/i
.i
:
1
and i
.1
, update the chosen value to the current node’s value.Here is the implementation of the above approach in C++:
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
// Definition for singly-linked list node.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode* head;
// Initialize with head of the linked list.
Solution(ListNode* head) {
this->head = head;
std::srand(std::time(nullptr)); // Seed for randomness
}
int getRandom() {
ListNode* current = head;
int result = current->val;
int index = 1;
while (current != nullptr) {
// Generate a random number between 1 and index (both inclusive)
if (std::rand() % index == 0) {
result = current->val;
}
index++;
current = current->next;
}
return result;
}
};
This ensures each node is picked with equal probability, making it an effective and efficient approach for the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?