318. Linked List Random Node
You receive the head of a singly linked list and an integer seed. Build a class Solution that is constructed once with (head, seed) and then answers any number of getRandom() calls, each returning the value of one node picked uniformly at random.
A checker cannot grade true randomness, so the random source is pinned. Keep an integer state, starting at seed. One draw in the range 0 … m − 1 works like this:
- update
state = (state × 1103515245 + 12345) mod 2³¹ - the drawn number is
state mod m
Every getRandom() call must make exactly one draw k = draw(n), where n is the number of nodes, and return the value of the k-th node counted from the head (0-indexed). The state carries over from one call to the next.
Follow-up: can you serve the calls without copying the list into an array — using only O(1) extra memory?
Example 1:
Input: head = [10, 1, 42, 7], seed = 7, then 3 × getRandom()
Output: [10, 1, 42]
Explanation: The three draws step the state 7 → 1282168116 → 642666333 → 712265938, giving k = 0, 1, 2 (mod 4) — the nodes holding 10, 1, and 42.
Example 2:
Input: head = [5], seed = 123, then 4 × getRandom()
Output: [5, 5, 5, 5]
Explanation: With a single node every draw is k = 0 (anything mod 1 is 0), so each call returns 5 — but the state still advances four times.
Constraints:
- 1 ≤ number of nodes ≤ 10⁴
- -10⁴ ≤ Node.val ≤ 10⁴
- 0 ≤ seed < 2³¹
- 1 ≤ q ≤ 100 getRandom() calls
- The product state * 1103515245 exceeds 32 bits — use 64-bit arithmetic.
Hints:
n is never handed to you — the constructor only gets head. Traverse the list once up front and remember how many nodes it has.
Easiest correct design: copy every value into an array in the constructor; each call is then one draw plus one index lookup. For the O(1)-memory follow-up, store only head and n: draw k = draw(n), then follow next exactly k times.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: head = [10, 1, 42, 7], seed = 7, calls = 3
Expected output: [10, 1, 42]