Linked List Random Node
Problem (restated)
Given a singly linked list of unknown length, getRandom() must return a node value uniformly at random. Do not store the whole list.
Intuition
Length is unknown and you get one pass per query. Algorithm R with k=1: at the i-th node, replace the chosen value with probability 1/i. After n nodes each value was chosen with probability 1/n.
Approaches
Algorithm R, k=1
UnverifiedIdea. Walk from the head. Count i from 1. Draw j in [0, i); if j == 0, keep this node’s value. First node is always chosen; later nodes steal the slot with the right odds.
Walkthrough. List 1 → 2 → 3. Node 1 kept (p=1). Node 2 replaces with 1/2. Node 3 replaces with 1/3. Each ends at 1/3.
Trade-offs. Caching into an array is O(n) space and only fair if the list never changes. Reservoir is the interview target for an unknown stream.
Show helper code
export class ListNode {
val: number;
next: ListNode | null;
constructor(val = 0, next: ListNode | null = null) {
this.val = val;
this.next = next;
}
}
export class ListNode {
val: number;
next: ListNode | null;
constructor(val = 0, next: ListNode | null = null) {
this.val = val;
this.next = next;
}
}
export class Solution {
private head: ListNode | null;
constructor(head: ListNode | number[] | null) {
if (Array.isArray(head)) {
const dummy = new ListNode(0);
let cur = dummy;
for (const v of head) {
cur.next = new ListNode(v);
cur = cur.next;
}
this.head = dummy.next;
} else {
this.head = head;
}
}
getRandom(): number {
let chosen = 0;
let i = 0;
let cur = this.head;
while (cur) {
i++;
if (Math.floor(Math.random() * i) === 0) chosen = cur.val;
cur = cur.next;
}
return chosen;
}
}
export class Solution {
private head: ListNode | null;
constructor(head: ListNode | number[] | null) {
if (Array.isArray(head)) {
const dummy = new ListNode(0);
let cur = dummy;
for (const v of head) {
cur.next = new ListNode(v);
cur = cur.next;
}
this.head = dummy.next;
} else {
this.head = head;
}
}
getRandom(): number {
let chosen = 0;
let i = 0;
let cur = this.head;
while (cur) {
i++;
if (Math.floor(Math.random() * i) === 0) chosen = cur.val;
cur = cur.next;
}
return chosen;
}
}
Template connection
Pick-one (k=1) on the Reservoir Sampling page: rand() < 1/i replaces the single-cell reservoir. Same proof as the k-sample template with k=1.
Reflection
- At the i-th node, draw in
[0, i). If the draw is 0, keep this value. The probability is1 / i. The length is unknown. - The first node is always the first candidate. The last node replaces it with probability
1 / n. - One node is itself. Storing the whole list and picking an index gives the same distribution, at
O(n)memory.