Problem 382

Abstract / Summary

Design a method to return a random node from a singly linked list efficiently each time it is called.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0382.py

class Solution:
    def __init__(self, head: Optional[ListNode]):
        self.head = head
        self.length = 0
        while head:
            self.length += 1
            head = head.next

    def getRandom(self) -> int:
        pos  = randint(0, self.length - 1)
        node = self.head
        while pos > 0:
            pos -= 1
            node = node.next

        return node.val
16 lines | 408 bytes | submitted September 11, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (400k+ submissions).

Typical patterns to solve this problem:
  • Linked List
  • Math
  • Randomized
  • Reservoir Sampling
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class that encapsulates a singly-linked list and offers a method to retrieve a random node value with uniform probability. The constructor walks the list once to record its length, while getRandom selects a random position and walks again to that node, returning its stored value.

Key Steps

Length Calculation in the Constructor

self.length = 0
while head:
    self.length += 1
    head = head.next

During object creation the code iterates from the supplied head node to the end of the list, incrementing a counter for each node encountered. This single pass establishes the total number of elements, which is later used to bound the random index generation.

Random Index Selection

pos = randint(0, self.length - 1)

A call to randint produces an integer pos that lies inclusively between 0 and self.length - 1. Because the range covers every possible zero-based position exactly once, each node receives an equal chance of being chosen.

Traversal to the Chosen Node

node = self.head
while pos > 0:
    pos -= 1
    node = node.next

Starting from the stored head, the loop advances pos steps forward. The decrement-first pattern ensures that after the loop terminates node references the element at the originally selected index.

Returning the Node Value

return node.val

The method concludes by exposing the val attribute of the located node, delivering the randomly selected data to the caller.

Edge Cases Handled

When the linked list contains exactly one element, self.length becomes 1. The call to randint(0, 0) deterministically yields 0, and the traversal loop does not execute because pos is already 0. Consequently, the sole node’s value is returned without unnecessary iteration.

For a list with many nodes, the constructor’s length computation still completes in a single linear pass, and each subsequent getRandom call performs a second linear walk limited to the randomly chosen offset. The algorithm therefore scales naturally with the size of the list, handling both very short and very long structures uniformly.

If the list were empty, self.length would remain 0. The range supplied to randint would be (0, -1), which is an invalid interval. In practice, the class is intended to be instantiated only with a non-empty list, and the code implicitly assumes that precondition, thereby avoiding additional conditional checks.

Performance Optimizations

The design precomputes the list length once during initialization, eliminating the need to recount nodes on every random selection. This reduces the overhead of getRandom to a single traversal whose length equals the randomly chosen index rather than the full list size.

By using randint from the standard library, the implementation leverages a fast, well-optimized random number generator without re-implementing distribution logic. The loop that advances to the target node decrements the counter before moving to the next pointer, which avoids an extra comparison after the final step.

Storing the original head reference allows direct access to the start of the list for each call, avoiding repeated reconstruction of the starting point. The overall approach balances the cost of an upfront O(N) pass with O(k) work per random retrieval, where k is the selected position, providing efficient average-case performance for repeated random accesses.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train where each carriage holds a secret number. The first part of this code is like a conductor walking from the very front of the train all the way to the back. As the conductor visits each carriage, they count how many there are in total so they know exactly how long the train is.

When it is time to pick a secret number, the code rolls special invisible dice to choose a random spot on the train. Once the number is picked, the code walks along the carriages again, stopping exactly at the spot chosen by the dice. When the code arrives at that special carriage, it peeks inside to see the number hidden there.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.52 | σ = 1.17

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
35 links | 23 authors | 10 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

11 solutions   September 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality