LeetCode 382: Linked List Random Node Solution

Master LeetCode problem 382 (Linked List Random Node), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

382. Linked List Random Node

Problem Explanation

Explanation

To solve this problem efficiently, we can use the Reservoir Sampling algorithm. The idea is to iterate through the linked list while maintaining a selected node that will be updated with a certain probability at each step to ensure each node has an equal chance of being chosen.

  • In the constructor, we initialize the selected node to the head of the linked list.
  • For each subsequent node, we generate a random number to decide whether to update the selected node with the current node.
  • This way, by the end of the iteration, the selected node will be one of the nodes from the linked list with equal probability.

The time complexity for getRandom() is O(n) where n is the number of nodes in the linked list. The space complexity is O(1) since we are not using any extra space.

Solution Code

import java.util.Random;

class Solution {
    ListNode head;
    Random random;

    public Solution(ListNode head) {
        this.head = head;
        this.random = new Random();
    }

    public int getRandom() {
        ListNode current = head;
        ListNode selected = null;
        int index = 0;

        while (current != null) {
            if (random.nextInt(++index) == 0) {
                selected = current;
            }
            current = current.next;
        }

        return selected.val;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 382 (Linked List Random Node)?

This page provides optimized solutions for LeetCode problem 382 (Linked List Random Node) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 382 (Linked List Random Node)?

The time complexity for LeetCode 382 (Linked List Random Node) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 382 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 382 in Java, C++, or Python.

Back to LeetCode Solutions