Skip to content
mlmentorship

Allocate one copy per original identity before following edges

Memoize copies before discovery, then preserve every ordered adjacency entry across cycles, shared nodes and multiple roots.

Published · 13 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Allocate one copy per original identity before following edges

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. One GraphNode reference, or None, in a finite graph with integer values and ordered neighbor lists. Output. Return the corresponding node in a newly allocated copy of the reachable component. Rules. Preserve node values, neighbor order, repeated entries, shared targets, cycles, and self-loops. Every copied edge must refer to copied nodes, never originals. Equal values do not make two nodes identical. Leave the original graph unchanged. Do not copy unreachable components; None returns None. Example. A triangle of original nodes O1, O2, and O3 becomes a triangle of C1, C2, and C3. Changing a copied node must not change its original.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Create one mapped copy per original node, then reproduce every adjacency entry between copies.

Problem trace

Allocate the mapped copy before discovering its neighbors

Input and goalMake a deep copy of a connected graph.
Create the first copyFor triangle O1-O2-O3, create C1 before traversal and enqueue O1. The map is {O1:C1}.
originalcloneO1O2O3C1
frontierO1
currentO1copiesO1->C1
edges
[O1 <-> O2, O1 <-> O3, O2 <-> O3]
edge labels
false
start
O1

Recognize it
A cyclic connected object must be deep-copied while preserving adjacency, so each original identity needs exactly one reusable copied identity before edges are wired.
Keep true
Every key in copies maps to exactly one clone, and after an original node is processed, its clone has one copied neighbor entry for every original neighbor processed in order.
Reuse it
When copying any cyclic object graph, allocate and memoize an object before traversing its references, then resolve every copied reference through that memo.
For triangle O1-O2-O3, create C1 before traversal and enqueue O1. The map is {O1:C1}. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: What happens when O2 reaches already-seen O1? Why is no original node present in the copied graph?
Full interview answer 13 min read

Create an independent copy of every node and edge reachable from a given graph node.

Problem

Input. One GraphNode reference, or None, in a finite graph with integer values and ordered neighbor lists.

Output. Return the corresponding node in a newly allocated copy of the reachable component.

Rules. Preserve node values, neighbor order, repeated entries, shared targets, cycles, and self-loops. Every copied edge must refer to copied nodes, never originals. Equal values do not make two nodes identical. Leave the original graph unchanged. Do not copy unreachable components; None returns None.

Example. A triangle of original nodes O1, O2, and O3 becomes a triangle of C1, C2, and C3. Changing a copied node must not change its original.

Picture

Before processing O1, create C1 and record O1 -> C1. When O1 discovers O2 and O3, allocate each copy once and enqueue each original once. Back edges find existing copies; they do not restart copying.

The memo’s keys are object identities, not numeric labels. Two different nodes labelled 7 still require two different copies.

Problem trace

Reuse the copy when a cycle returns; never link back to originals

Worked example: a cycle reuses the already-created copyWhen B reaches A again, the original-to-copy map returns A-prime. Linking to original A would corrupt the clone boundary.The copied back edge stays inside thecopy enclosureOriginal cycle: A and BABReuse A-primeA'B'copy-maplookupB-prime links to A-prime, never tooriginal A.
Read it this way: When B reaches A again, the original-to-copy map returns A-prime. Linking to original A would corrupt the clone boundary. If B-prime links to original A instead, which enclosure does that supposed clone leave?
Reference drawing

Problem trace

Reuse the copy when a cycle returns; never link back to originals

Worked example: a cycle reuses the already-created copyWhen B reaches A again, the original-to-copy map returns A-prime. Linking to original A would corrupt the clone boundary.The copied back edge stays inside thecopy enclosureOriginal cycle: A and BABReuse A-primeA'B'copy-maplookupB-prime links to A-prime, never tooriginal A.
Execution trace
Input and goalMake a deep copy of a connected graph.
Create the first copyFor triangle O1-O2-O3, create C1 before traversal and enqueue O1. The map is {O1:C1}.
originalcloneO1O2O3C1
frontierO1
currentO1copiesO1->C1
edges
[O1 <-> O2, O1 <-> O3, O2 <-> O3]
edge labels
false
start
O1

Recognize it
A cyclic connected object must be deep-copied while preserving adjacency, so each original identity needs exactly one reusable copied identity before edges are wired.
Keep true
Every key in copies maps to exactly one clone, and after an original node is processed, its clone has one copied neighbor entry for every original neighbor processed in order.
Reuse it
When copying any cyclic object graph, allocate and memoize an object before traversing its references, then resolve every copied reference through that memo.
For triangle O1-O2-O3, create C1 before traversal and enqueue O1. The map is {O1:C1}. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: What happens when O2 reaches already-seen O1? Why is no original node present in the copied graph?
Read it this way: When B reaches A again, the original-to-copy map returns A-prime. Linking to original A would corrupt the clone boundary. If B-prime links to original A instead, which enclosure does that supposed clone leave?

Invariant: every discovered original already has exactly one allocated copy, although its outgoing adjacency may still be incomplete. For each adjacency entry, append the mapped neighbor even when that neighbor was discovered earlier.

Code

This reference supplies identity-hashable GraphNode objects. It does not define value-based equality, so equal labels do not merge dictionary keys.

from __future__ import annotations
from collections import deque

class GraphNode:
   def __init__(self, val: int = 0, neighbors: list[GraphNode] | None = None) -> None:
      self.val = val
      self.neighbors = neighbors or []


def clone_graph(node: GraphNode | None) -> GraphNode | None:
   if node is None:
      return None

   copies = {node: GraphNode(node.val)}
   queue = deque([node])

   while queue:
      current = queue.popleft()
      for neighbor in current.neighbors:
         if neighbor not in copies:
            copies[neighbor] = GraphNode(neighbor.val)
            queue.append(neighbor)
         copies[current].neighbors.append(copies[neighbor])
   return copies[node]

For reachable nodes and adjacency entries, time is . Memo and queue use auxiliary space. Copied nodes and adjacency separately occupy output space. Repeated neighbor entries count separately in . Original nodes and lists remain unchanged.

Failure Check

Memoizing after following edges can recurse forever on a cycle. A visited Boolean alone cannot identify the copied target. Skipping edges to visited nodes drops back edges, shared references, and repeated entries. Keying by val incorrectly merges distinct equal-valued originals.

Change the Traversal

New task: Use recursive DFS while preserving the same copying contract.

Picture and change: Keep allocation before descent. Every recursive revisit returns the already allocated copy. Use the supplied GraphNode above.

def clone_graph_dfs(node):
   copies = {}
   def visit(original):
      if original is None:
         return None
      if original not in copies:
         copies[original] = GraphNode(original.val)
         copies[original].neighbors = [visit(neighbor) for neighbor in original.neighbors]
      return copies[original]
   return visit(node)

Check: Give two distinct 7 nodes a back edge and two repeated references to the second node. Their copies remain distinct, repeated references share one target, and the back edge closes inside the copy. Time and output bounds remain unchanged; recursive depth can reach and exceed Python’s limit.

Use when: DFS presentation is useful and recursive depth is acceptable.

Change the Root Boundary

New task: Copy several roots, including disconnected or overlapping components.

Picture and change: Seed one shared memo and queue. Pass a sequence, since roots is read twice.

def clone_roots(roots):
   copies, queue = {}, deque()
   for root in roots:
      if root is not None and root not in copies:
         copies[root] = GraphNode(root.val)
         queue.append(root)
   while queue:
      original = queue.popleft()
      for neighbor in original.neighbors:
         if neighbor not in copies:
            copies[neighbor] = GraphNode(neighbor.val)
            queue.append(neighbor)
         copies[original].neighbors.append(copies[neighbor])
   return [None if root is None else copies[root] for root in roots]

Check: [first, second, first, None] returns the same copied first twice, an independent copied second, and None. Shared reachable nodes are copied once across roots. For roots, time is and output space is ; memo/queue remain . Keep the reference’s deque import.

Use when: Multiple entry points define the requested ownership boundary.

Transfer Check

Why is the memo more than a visited set?

Answer

It identifies the unique copied target needed for every reconstructed reference. Discovery alone prevents repeated work but cannot rebuild the edges. Compare tree copying when cycles and shared nodes are excluded by contract.