Algo-Sim › Linked Lists

Copy List with Random Pointer

Medium · Linked Lists · step through it in Java, Python and C++ on your own input

Deep-copy a list whose nodes also have a random pointer: clone every node into a map, then wire next and random through it.

Problem

Each node of the list has a next pointer and a random pointer that points to any node of the list or to null. Build a deep copy: brand-new nodes whose next and random pointers mirror the original's structure, sharing no node with it.

Constraints

Edge cases to test

Follow-up questions

How do you do it without a hash map?
Interleave copies after each original (A → A′ → B → B′), set A′.random = A.random.next, then split the lists: O(n) time, O(1) extra.
How does this generalise?
Cloning any graph needs a map from original to copy to handle shared and cyclic references (LC 133).

Solution

Java

public Node copyRandomList(Node head) {
    Map<Node, Node> copy = new HashMap<>();
    for (Node curr = head; curr != null; curr = curr.next) {
        copy.put(curr, new Node(curr.val));
    }
    for (Node curr = head; curr != null; curr = curr.next) {
        copy.get(curr).next = copy.get(curr.next);
        copy.get(curr).random = copy.get(curr.random);
    }
    return copy.get(head);
}

Python

def copy_random_list(head):
    copy = {None: None}
    curr = head
    while curr:
        copy[curr] = Node(curr.val)
        curr = curr.next
    curr = head
    while curr:
        copy[curr].next = copy[curr.next]
        copy[curr].random = copy[curr.random]
        curr = curr.next
    return copy[head]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    Node *copyRandomList(Node *head) {
        unordered_map<Node *, Node *> copy = {};
        for (Node *curr = head; curr != nullptr; curr = curr->next) {
            copy[curr] = new Node(curr->val);
        }
        for (Node *curr = head; curr != nullptr; curr = curr->next) {
            copy[curr]->next = copy[curr->next];
            copy[curr]->random = copy[curr->random];
        }
        return copy[head];
    }
};

More Linked Lists problems