← Home

382. Linked List Random Node

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
382

This is one of those problems where the clean idea matters more than the amount of code. For 382. Linked List Random Node, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are getRandom.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 36 ms, faster than 88.32% of C++ online submissions for Linked List Random Node.
02//Memory Usage: 14.4 MB, less than 100.00% of C++ online submissions for Linked List Random Node.
03/**
04 * Definition for singly-linked list.
05 * struct ListNode {
06 *     int val;
07 *     ListNode *next;
08 *     ListNode(int x) : val(x), next(NULL) {}
09 * };
10 */
11class Solution {
12public:
13    vector<int> v;
14    /** @param head The linked list's head.
15        Note that the head is guaranteed to be not null, so it contains at least one node. */
16    Solution(ListNode* head) {
17        ListNode* cur = head;
18        while(cur){
19            v.push_back(cur->val);
20            cur = cur->next;
21        }
22    }
23    
24    /** Returns a random node's value. */
25    int getRandom() {
26        return v[rand()%v.size()];
27    }
28};
29
30/**
31 * Your Solution object will be instantiated and called as such:
32 * Solution* obj = new Solution(head);
33 * int param_1 = obj->getRandom();
34 */
35 
36//Reservoir sampling
37//https://leetcode.com/problems/linked-list-random-node/discuss/85662/Java-Solution-with-cases-explain
38//Runtime: 40 ms, faster than 60.00% of C++ online submissions for Linked List Random Node.
39//Memory Usage: 14 MB, less than 100.00% of C++ online submissions for Linked List Random Node.
40/**
41 * Definition for singly-linked list.
42 * struct ListNode {
43 *     int val;
44 *     ListNode *next;
45 *     ListNode(int x) : val(x), next(NULL) {}
46 * };
47 */
48class Solution {
49public:
50    ListNode *head;
51    /** @param head The linked list's head.
52        Note that the head is guaranteed to be not null, so it contains at least one node. */
53    Solution(ListNode* head) {
54        this->head = head;
55    }
56    
57    /** Returns a random node's value. */
58    int getRandom() {
59        ListNode *cur = head, *candidate = head;
60        int count = 0;
61        while(cur != nullptr){
62            if(rand()%(count+1) == count){
63                //select the (k+1) th element with prob = 1/(k+1)
64                candidate = cur;
65            }
66            cur = cur->next;
67            count++;
68        }
69        return candidate->val;
70    }
71};
72
73/**
74 * Your Solution object will be instantiated and called as such:
75 * Solution* obj = new Solution(head);
76 * int param_1 = obj->getRandom();
77 */

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.