MediumNo. 0138

Copy List with Random Pointer — LeetCode 138 Python Solution

Topics
Hash Table, Linked List
Reading time
5 min

The problem

A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list.

Example

Input
head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output
[[7,null],[13,0],[11,4],[10,2],[1,0]]

Python solution

PythonSolution
"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""


class Solution:
    def copyRandomList(self, head: "Optional[Node]") -> "Optional[Node]":
        d = {}
        dummy = tail = Node(0)
        cur = head
        while cur:
            node = Node(cur.val)
            tail.next = node
            tail = tail.next
            d[cur] = node
            cur = cur.next
        cur = head
        while cur:
            d[cur].random = d[cur.random] if cur.random else None
            cur = cur.next
        return dummy.next

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 138. Copy List with Random Pointer is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0141Linked List CycleEasy
0142Linked List Cycle IIMedium
0146LRU CacheMedium
0160Intersection of Two Linked ListsEasy
0355Design TwitterMedium
0432All O`one Data StructureHard

Frequently asked questions

How hard is LeetCode 138. Copy List with Random Pointer?

LeetCode 138. Copy List with Random Pointer is rated Medium on LeetCode.

What is the time complexity of LeetCode 138. Copy List with Random Pointer?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 138. Copy List with Random Pointer?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 138. Copy List with Random Pointer cover?

LeetCode 138. Copy List with Random Pointer is tagged Hash Table and Linked List on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.