Problem 138

Abstract / Summary

You must create a deep copy of a linked list where each node has a random pointer, ensuring the new list mirrors the original structure and connections.

Note

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

Python 0138.py

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        if not head:
            return None

        # inject IDs
        id = 0
        current = head
        while current:
            current.id = id
            id += 1
            current = current.next

        all = []
        for _ in range(id):
            all.append(Node(0, None, None))

        # replicate
        id = 0
        current = head
        while current:
            all[id].val = current.val
            if id < len(all) - 1:
                all[id].next = all[id + 1]
            if current.random:
                all[id].random = all[current.random.id]

            current = current.next
            id += 1

        return all[0]
31 lines | 785 bytes | submitted August 31, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 63% (3+ million submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Linked List
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 creates a deep copy of a singly-linked list where each node contains an additional random pointer that may reference any node in the list or be None. The algorithm proceeds in three conceptual phases: a preliminary pass that annotates each original node with a unique identifier, allocation of a parallel array of new nodes, and a second pass that transfers values and reconstructs both the next and random links. By using an auxiliary array indexed by the injected identifiers, the method resolves random references in constant time during the second traversal.

Phase 1 - Injecting identifiers

The first loop walks the original list from the head, assigning a monotonically increasing integer to a newly created attribute id on each node. This identifier serves as a stable key that can later be used to locate the corresponding copy in the auxiliary array.

if not head:
    return None

id = 0
current = head
while current:
    current.id = id
    id += 1
    current = current.next

The guard if not head: handles the edge case where the input list is empty, returning None immediately without further processing.

Phase 2 - Pre-allocating the copy nodes

After the identifier injection, the total number of nodes is known (id). An array named all is created with that exact length, and each slot is filled with a freshly instantiated node whose fields are initially placeholders (val=0, next=None, random=None). This pre-allocation avoids repeated node creation inside the main copy loop and guarantees that each index in the array corresponds to a unique node in the new list.

all = []
for _ in range(id):
    all.append(Node(0, None, None))

The use of a simple list comprehension-style loop ensures that the allocation cost is proportional to the number of original nodes and that the memory layout is contiguous, which can improve cache locality when the array is accessed repeatedly in the next phase.

Phase 3 - Replicating values and wiring pointers

A second traversal of the original list copies the payload (val) into the matching node in all. The next pointer of each new node is set to the subsequent element in the array, except for the final node where no forward link is required. For the random pointer, the algorithm checks whether the original node’s random field is non-null; if it is, the previously stored identifier (current.random.id) is used to fetch the appropriate copy from all. This direct indexing eliminates the need for a hash map or additional search.

id = 0
current = head
while current:
    all[id].val = current.val
    if id < len(all) - 1:
        all[id].next = all[id + 1]
    if current.random:
        all[id].random = all[current.random.id]

    current = current.next
    id += 1

The conditional if current.random: safeguards against dereferencing a None random pointer, thereby correctly handling nodes whose random reference is absent. The boundary check if id < len(all) - 1: prevents an out-of-range assignment for the tail node’s next field.

Return value

After the replication loop finishes, the head of the newly constructed list resides at index 0 of the auxiliary array. The method returns this reference, delivering a fully independent copy whose structure mirrors the original, including all next and random relationships.

return all[0]

Edge-case handling

The algorithm explicitly addresses two important edge conditions. First, an empty input list triggers an early return of None, ensuring that no further work is performed and that the caller receives a correctly typed empty result. Second, nodes whose random pointer is None are left with a None random reference in the copy, because the conditional guard prevents any attempt to resolve a non-existent identifier.

Performance-related choices

The design avoids multiple passes over the list for mapping purposes. By embedding a numeric identifier directly onto each original node, the code eliminates the need for an external dictionary that would otherwise map original nodes to their copies. This in-place tagging reduces auxiliary memory overhead to the size of the identifier field, which is negligible compared to the array of new nodes.

Pre-allocating the entire array of copy nodes before populating fields means that each node is created exactly once, and subsequent field assignments are simple attribute writes. This approach benefits from predictable memory allocation patterns and improves data locality, as the array elements are stored contiguously in memory. The direct index-based lookup for random pointers yields constant-time resolution, avoiding the logarithmic or linear costs associated with search-based strategies.

Overall, the implementation achieves a linear traversal count (two passes) and leverages straightforward data structures to keep the runtime efficient while maintaining clear and deterministic behavior across all supported input configurations.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a line of friends holding hands, where each friend has a special note and sometimes points to another friend further down the line. To make an exact copy, the first step is to walk down the line and give every friend a unique number tag so everyone can be identified easily.

Once every friend has a numbered tag, a brand new line of empty copies is built, one for each original friend. Now, the process happens again by walking through the original line once more. For each original friend, the corresponding copy is found using the number tag. The copied friend is given the same note, told which friend is next in line, and shown which friend they should point to based on the random connection from the original. By the time the walk is finished, there is a perfect second line of friends that looks and acts just like the first one.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 5.5 | μ = 5.27 | σ = 1.53

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 C# JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
56 links | 40 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Copy List with Random Pointer - Linked List - Leetcode 138'
NeetCode 11 mins
Copy List with Random Pointer - Linked List - Leetcode 138
YouTube video 'Copy List with Random Pointer | 2 Approaches | Clear Intuition | Dry Run | Microsoft| Leetcode - 138'
codestorywithMIK 46 mins
Copy List with Random Pointer | 2 Approaches | Clear Intuition | Dry Run | Microsoft| Leetcode - 138
YouTube video 'Copy List With Random Pointers | Leetcode 138. Copy List with Random Pointer'
Pepcoding 33 mins
Copy List With Random Pointers | Leetcode 138. Copy List with Random Pointer
YouTube video 'Copy List with Random Pointer - Leetcode 138 - Linked Lists (Python)'
Greg Hogg 8 mins
Copy List with Random Pointer - Leetcode 138 - Linked Lists (Python)
YouTube video 'Copy List with Random Pointer | Live Coding with Explanation | Leetcode #138'
Algorithms Made Easy 11 mins
Copy List with Random Pointer | Live Coding with Explanation | Leetcode #138
YouTube video 'Copy List with Random Pointer || Leetcode 138 || 1 Variant Question Big Tech Actually Asks'
Coding with Minmer 24 mins
Copy List with Random Pointer || Leetcode 138 || 1 Variant Question Big Tech Actually Asks
YouTube video 'COPY LIST WITH RANDOM POINTER | PYTHON | LEETCODE # 138'
Cracking FAANG 15 mins
COPY LIST WITH RANDOM POINTER | PYTHON | LEETCODE # 138
YouTube video 'Copy List with Random Pointer | Leetcode 138 | Linked List | Day-12'
Ayushi Sharma 30 mins
Copy List with Random Pointer | Leetcode 138 | Linked List | Day-12
YouTube video '138. Copy List with Random Pointer  II Linked List II Make Deep Copy of Linked List'
Aryan Mittal 18 mins
138. Copy List with Random Pointer II Linked List II Make Deep Copy of Linked List
YouTube video 'Copy List with Random Pointer | LeetCode 138 | Linked List | Facebook Amazon Microsoft'
Naresh Gupta 16 mins
Copy List with Random Pointer | LeetCode 138 | Linked List | Facebook Amazon Microsoft
YouTube video 'Leetcode - Copy List with Random Pointer (Python)'
Timothy H Chang 10 mins
Leetcode - Copy List with Random Pointer (Python)
YouTube video '138. Copy List with Random Pointer || NEETCODE 150'
TechWithSaumya 32 mins
138. Copy List with Random Pointer || NEETCODE 150
YouTube video 'Copy List with Random Pointer | Leetcode 138'
Coding Decoded 15 mins
Copy List with Random Pointer | Leetcode 138
YouTube video 'LeetCode 138. Copy List with Random Pointer  [IN 3 MINUTES]'
Code with Carter 4 mins
LeetCode 138. Copy List with Random Pointer [IN 3 MINUTES]
YouTube video 'Daily Leetcode #1253: Sep 05, 2023 - 138. Copy List with Random Pointer'
Programming Live with Larry 9 mins
Daily Leetcode #1253: Sep 05, 2023 - 138. Copy List with Random Pointer
YouTube video 'Leetcode Solution - 138 Copy List with Random Pointer'
John Leonardo 8 mins
Leetcode Solution - 138 Copy List with Random Pointer
YouTube video '138 || Copy List with Random Pointer || C++ || Leetcode Daily Challenge'
CodeFreaks 12 mins
138 || Copy List with Random Pointer || C++ || Leetcode Daily Challenge
YouTube video '138. Copy List with Random Pointer | Daily Leetcode Challenge | September | C++ | Java'
Mayur Programming Club 19 mins
138. Copy List with Random Pointer | Daily Leetcode Challenge | September | C++ | Java
YouTube video 'LeetCode 138. Copy List with Random Pointer'
Happy Coding 12 mins
LeetCode 138. Copy List with Random Pointer
YouTube video 'Daily Leetcode #711: Mar 12, 2022 - 138. Copy List with Random Pointer'
Programming Live with Larry 11 mins
Daily Leetcode #711: Mar 12, 2022 - 138. Copy List with Random Pointer
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

27 solutions   August 31, 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