Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
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.valrandom_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 <= 104Node.random is null or is pointing to some node in the linked list.Problem summary: 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Linked List
[[7,null],[13,0],[11,4],[10,2],[1,0]]
[[1,1],[2,1]]
[[3,null],[3,0],[3,null]]
clone-graph)clone-binary-tree-with-random-pointer)clone-n-ary-tree)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #138: Copy List with Random Pointer
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
Map<Node, Node> d = new HashMap<>();
Node dummy = new Node(0);
Node tail = dummy;
for (Node cur = head; cur != null; cur = cur.next) {
Node node = new Node(cur.val);
tail.next = node;
tail = node;
d.put(cur, node);
}
for (Node cur = head; cur != null; cur = cur.next) {
d.get(cur).random = cur.random == null ? null : d.get(cur.random);
}
return dummy.next;
}
}
// Accepted solution for LeetCode #138: Copy List with Random Pointer
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Random *Node
* }
*/
func copyRandomList(head *Node) *Node {
dummy := &Node{}
tail := dummy
d := map[*Node]*Node{}
for cur := head; cur != nil; cur = cur.Next {
node := &Node{Val: cur.Val}
d[cur] = node
tail.Next = node
tail = node
}
for cur := head; cur != nil; cur = cur.Next {
if cur.Random != nil {
d[cur].Random = d[cur.Random]
}
}
return dummy.Next
}
# Accepted solution for LeetCode #138: Copy List with Random Pointer
"""
# 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
// Accepted solution for LeetCode #138: Copy List with Random Pointer
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #138: Copy List with Random Pointer
// /*
// // Definition for a Node.
// class Node {
// int val;
// Node next;
// Node random;
//
// public Node(int val) {
// this.val = val;
// this.next = null;
// this.random = null;
// }
// }
// */
//
// class Solution {
// public Node copyRandomList(Node head) {
// Map<Node, Node> d = new HashMap<>();
// Node dummy = new Node(0);
// Node tail = dummy;
// for (Node cur = head; cur != null; cur = cur.next) {
// Node node = new Node(cur.val);
// tail.next = node;
// tail = node;
// d.put(cur, node);
// }
// for (Node cur = head; cur != null; cur = cur.next) {
// d.get(cur).random = cur.random == null ? null : d.get(cur.random);
// }
// return dummy.next;
// }
// }
// Accepted solution for LeetCode #138: Copy List with Random Pointer
/**
* Definition for _Node.
* class _Node {
* val: number
* next: _Node | null
* random: _Node | null
*
* constructor(val?: number, next?: _Node, random?: _Node) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* this.random = (random===undefined ? null : random)
* }
* }
*/
function copyRandomList(head: _Node | null): _Node | null {
const d: Map<_Node, _Node> = new Map();
const dummy = new _Node();
let tail = dummy;
for (let cur = head; cur; cur = cur.next) {
const node = new _Node(cur.val);
tail.next = node;
tail = node;
d.set(cur, node);
}
for (let cur = head; cur; cur = cur.next) {
d.get(cur)!.random = cur.random ? d.get(cur.random)! : null;
}
return dummy.next;
}
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.