Skip to content
DSA Patterns
Menu
Language
Reservoir SamplingLC #3822 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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

Unverified
Time O(n) getRandomSpace O(1)

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

Solution
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 is 1 / 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.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 7
1/7

Stream of unknown length. Want k=1 uniform sample in one pass, O(1) extra memory.

10
0
20
1
30
2
40
3
Statek=1res=∅

pick with probability 1/i

Key:CurrentActive rangeMatchSettledEliminated