Taro Logo

Copy List with Random Pointer

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+18
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
894 views
Topics:
Linked ListsRecursionArrays

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. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.

For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.

Return the head of the copied linked list.

The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

  • val: an integer representing Node.val
  • random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.

Your code will only be given the head of the original linked list.

Example 1:

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

Example 2:

Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]

Example 3:

Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]

Constraints:

  • 0 <= n <= 1000
  • -104 <= Node.val <= 104
  • Node.random is null or is pointing to some node in the linked list.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the linked list be empty (i.e., is `head` ever `null`), and if so, should the function return `null`?
  2. Are node values restricted to standard integers, or could they be any data type?
  3. Can the `random` pointer point to a node that appears earlier, later, or even to the node itself?
  4. Are duplicate values allowed within the nodes of the linked list, and if so, does our cloning logic need to handle them distinctly?
  5. Are we guaranteed that the original linked list is properly formed and does not contain cycles, or do we need to guard against cyclic structures?

Brute Force Solution

Approach

Imagine you have a complex network of people connected by two types of threads, and you need to build an exact duplicate of the entire group. The brute force approach involves creating all the new people first, and then exhaustively searching through the original group to figure out how every single connection should be re-attached for the new copies.

Here's how the algorithm would work step-by-step:

  1. Look at the original group and create a brand new, empty copy for every single person in the line, without connecting any threads yet.
  2. Go back to the very beginning of the original group to start the process of wiring everything up.
  3. For the current person you are looking at, check which regular neighbor they point to next in line.
  4. Search through the entire original group from the very start to find that exact same neighbor, and then look over at your newly created copies to see which copy corresponds to that neighbor.
  5. Connect the regular thread from your current copy to that corresponding neighbor's copy.
  6. Go back to the original group to check which random person the current person points to with their special random thread.
  7. Search the original group all over again to find that random person, locate their corresponding copy, and connect the special random thread from your current copy to them.
  8. Repeat this entire search and connection process for every single person in the group until every regular thread and every random thread is perfectly duplicated.

Code Implementation

class Node:
    def __init__(self, val=0, next=None, random=None):
        self.val = val
        self.next = next
        self.random = random

def copyRandomList(head):
    if not head:
        return None

    # We first generate all nodes without connections so they exist in memory to reference later
    original_nodes = []
    copied_nodes = []
    current_original = head
    while current_original:
        original_nodes.append(current_original)
        copied_nodes.append(Node(current_original.val))
        current_original = current_original.next

    # We iterate through the original list again to find index positions for every pointer target
    for original_index in range(len(original_nodes)):
        target_next = original_nodes[original_index].next
        if target_next:
            next_target_index = original_nodes.index(target_next)
            copied_nodes[original_index].next = copied_nodes[next_target_index]

        target_random = original_nodes[original_index].random
        if target_random:
            random_target_index = original_nodes.index(target_random)
            copied_nodes[original_index].random = copied_nodes[random_target_index]

    # We return the head of the newly created copy list since all structural threads are fully wired
    return copied_nodes[0]

Big(O) Analysis

Time Complexity
O(n²) – For each of the n nodes in the linked list, the algorithm must perform an exhaustive search through the entire list to locate the correct target nodes for both the next and random pointers. Since we repeat this linear search operation for every single one of the n nodes, we visit nodes inside nested passes. This leads to approximately n * n operations total, which simplifies to a quadratic time complexity of O(n²).
Space Complexity
O(N) – The brute force approach described requires building a brand new, empty copy for every single person in the line. This means we must store N newly created nodes in memory to form the duplicated group. Additionally, establishing connections requires no extra dynamic data structures beyond the output list itself, but storing the duplicated nodes consumes memory proportional to the input size N. Therefore, the auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

To duplicate a linked list with extra random connections, the best method avoids getting confused by trying to set up all the random links at the same time. Instead, it cleverly weaves the cloned items right next to their original counterparts so that finding the correct random destination becomes completely obvious.

Here's how the algorithm would work step-by-step:

  1. Begin at the very beginning of the original line of items and walk through it one by one.
  2. For every single item you encounter, create an identical twin right next to it, sandwiching the new twin between the current item and whatever item originally came next.
  3. Continue this process until every original item has a fresh twin sitting immediately to its right, effectively doubling the length of the entire chain with alternating original and cloned items.
  4. Take a second walk through this newly expanded chain, focusing only on the random connections. Because every original item now sits directly beside its twin, you can easily look at where the original item's random connection points, and simply point the twin's random connection to the immediate neighbor of that target.
  5. Once all the random connections are accurately copied over, take a final walk through the chain to carefully untangle the two intertwined lines.
  6. Restore the original line so it looks exactly as it did in the beginning, and gently separate the twin items to form a completely independent, newly cloned line.
  7. Check that both lines are fully intact and properly separated, leaving you with an exact, independent duplicate of the original list.

Code Implementation

class Node:
    def __init__(self, val: int, next: 'Node' = None, random: 'Node' = None):
        self.val = val
        self.next = next
        self.random = random


def copyRandomList(head: 'Node') -> 'Node':
    if not head:
        return None

    current_node = head
    while current_node:
        cloned_node = Node(current_node.val)
        cloned_node.next = current_node.next
        current_node.next = cloned_node
        current_node = cloned_node.next

    # Intertwine clones next to originals to easily map out random pointers.    current_node = head
    while current_node:
        if current_node.random:
            current_node.next.random = current_node.random.next
        current_node = current_node.next.next

    # Assign random pointers to the cloned nodes using the interleaved structure.    current_node = head
    cloned_head = head.next
    while current_node:
        cloned_node = current_node.next
        current_node.next = cloned_node.next
        current_node = current_node.next
        if cloned_node.next:
            cloned_node.next = cloned_node.next.next
        current_node = current_node.next

    # Restore the original list and separate the cloned list entirely.
    return cloned_head

Big(O) Analysis

Time Complexity
O(n) – The algorithm processes the linked list of length n across three distinct sequential passes. The first pass traverses all n nodes to create and interleave the cloned twins. The second pass revisits all n nodes to assign the random pointers for the newly created twins. The final pass iterates through all n nodes once more to cleanly separate the intertwined original and cloned lists. Since these operations scale linearly with the number of nodes rather than through nested iteration, the total operations scale proportionally to 3n, which simplifies to O(n).
Space Complexity
O(1) – This approach weaves the cloned twin nodes directly into the existing linked list alongside their original counterparts, eliminating the need for any hash maps, temporary lists, or recursion stacks. We only allocate a constant number of pointer variables to track traversal during the sandwiching, random pointer assignment, and untangling phases. Because no additional data structures scale with the input size N, the auxiliary memory footprint remains completely fixed. Therefore, the overall space complexity simplifies to Big O of 1.

Edge Cases

Null head pointer representing an empty list
How to Handle:
Return null immediately since there are no nodes to copy.
Linked list with a single node whose random pointer points to itself
How to Handle:
The node creation logic maps the single node to its copy and assigns its random pointer to reference the copied node.
Linked list with a single node whose random pointer is null
How to Handle:
The algorithm creates the cloned node with its next and random pointers correctly set to null.
Nodes with random pointers pointing backwards to earlier nodes in the list
How to Handle:
A hash map or interweaving technique ensures previously created nodes are accessible when resolving random pointers.
Nodes with random pointers pointing forwards to later nodes not yet visited
How to Handle:
A multi-pass approach or map-based lookup guarantees forward references are established once all nodes are instantiated.
All nodes having identical integer values
How to Handle:
Using node object references as keys in the hash map instead of node values prevents collisions and ambiguity.
Extremely long linked lists causing deep recursion stacks
How to Handle:
Iterative approaches or careful pointer manipulation are used to prevent stack overflow errors common in recursive deep copies.
Random pointers forming complex cyclical references among multiple nodes
How to Handle:
The mapping structure correctly resolves cycles by looking up existing clones regardless of traversal order.
0/75 completed