Leetcode 382: Linked List Random Node

grid47
grid47
Exploring patterns and algorithms
Sep 29, 2024 5 min read

A glowing linked list where the randomly selected node is softly highlighted.
Solution to LeetCode 382: Linked List Random Node Problem

Given a singly linked list, implement a class that supports the initialization of the list and the ability to return a random node’s value with equal probability.
Problem
Approach
Steps
Complexity
Input: The input consists of the initialization of a linked list followed by multiple calls to the getRandom method.
Example: Example input: [[1, 2, 3]] for initialization followed by calls to getRandom.
Constraints:
• 1 <= Number of nodes <= 10^4
• -10^4 <= Node.val <= 10^4
• At most 10^4 calls to getRandom.
Output: The output is a sequence of results from each getRandom() call, where each result corresponds to a random node's value from the list.
Example: Example output: [null, 2, 3, 1, 2, 3]
Constraints:
• Each getRandom() call returns one node's value randomly chosen from the linked list.
Goal: The goal is to implement getRandom in such a way that each node in the list has an equal probability of being chosen.
Steps:
• Initialize the linked list with the given nodes.
• Iterate through the linked list, maintaining a count of the nodes encountered.
• At each node, decide randomly whether to select that node or not using a probability of 1/i, where i is the number of nodes visited so far.
Goal: The solution must be efficient with a time complexity of O(n) and space complexity of O(1), where n is the number of nodes in the linked list.
Steps:
• Ensure O(n) time complexity for the getRandom method.
• Ensure O(1) space complexity for the getRandom method, meaning no extra space should be used other than for iterating through the list.
Assumptions:
• The linked list is not empty.
• The list can contain a maximum of 10^4 nodes.
Input: Example 1: [[], [1], [2], [2], [], [1], [2], []]
Explanation: For each call to getRandom, one of the nodes (1, 2, or 3) should be selected randomly with equal probability.

Input: Example 2: [[], [5], [10], [15], [], [5], [10], [15]]
Explanation: Here, 5, 10, or 15 is selected randomly on each call to getRandom.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus