LeetCode 138: Copy List with Random Pointer — Python Solution

LeetCode 138: Copy List with Random Pointer is a Medium linked list problem. This Python walkthrough develops a node-to-copy map solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicLinked List
Reusable patternnode-to-copy map
ComplexityO(n) time and O(n) space

Recognizing the pattern

Linked-list solutions depend on preserving reachability while rewiring a constant number of pointers. Dummy nodes remove many head-only special cases.

For this problem specifically, create one copy per original node, then wire next and random pointers by looking up their copied targets. The invariant worth writing beside the code is: The map contains the unique clone for every original node before any cloned edge is assigned.

Step-by-step algorithm

  1. Identify the input state consumed by copyRandomList(head) and initialize the data required by the node-to-copy map pattern.
  2. Create one copy per original node, then wire next and random pointers by looking up their copied targets.
  3. After each update, verify the page’s central invariant: The map contains the unique clone for every original node before any cloned edge is assigned.
  4. Finish only after the boundary behavior is covered: Random pointers may be null, self-referential, or point backward.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

class Solution:
    def copyRandomList(self, head):
        if not head:
            return None
        copies = {}
        current = head
        while current:
            copies[current] = Node(current.val)
            current = current.next
        current = head
        while current:
            copies[current].next = copies.get(current.next)
            copies[current].random = copies.get(current.random)
            current = current.next
        return copies[head]

Reading the implementation

The main entry point is copyRandomList(head). The named working state includes copies, current; those variables make the node-to-copy map state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, create one copy per original node, then wire next and random pointers by looking up their copied targets.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Create one copy per original node, then wire next and random pointers by looking up their copied targets. Each update records the current item without invalidating earlier decisions; consequently, the map contains the unique clone for every original node before any cloned edge is assigned.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n) time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Copying values into an array makes indexing easy but abandons the intended pointer-space constraint and node identity. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

a,b=Node(7),Node(13); a.next=b; b.random=a; copied=Solution().copyRandomList(a); assert copied is not a and copied.next.random is copied

Common mistakes and edge cases

  • Problem-specific boundary: Random pointers may be null, self-referential, or point backward.
  • Pattern-level pitfall: Save the next node before changing a link, terminate reused tails, and check whether the original head can be removed.
  • Invariant check: after every update, confirm that the map contains the unique clone for every original node before any cloned edge is assigned.

Interview review checklist

  • Explain why node-to-copy map matches the structure of this input.
  • State the invariant in one sentence before tracing code: The map contains the unique clone for every original node before any cloned edge is assigned.
  • Derive O(n) time and O(n) space from how many times each element or state is visited.
  • Test the boundary explicitly: Random pointers may be null, self-referential, or point backward.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 21. Merge Two Sorted Lists · Next: 92. Reverse Linked List II