CodeArchon

mediumGraphsFacebookGooglePocket Gems

Social Graph Mirror

A privacy pipeline deep-copies an entire friends-of-friends graph (preserving cycles) before sharing with downstream analytics.

Given a reference of a node in a connected undirected graph, return a deep copy of the graph.

Choose approach

1
cur
2
3
4
1/5
Narrationstep 1 of 5

Clone node 1; store original→copy mapping.

1def cloneGraph(node):
2 if not node: return None
3 seen = {}
4 def dfs(n):
5 if n in seen: return seen[n]
6 copy = Node(n.val)
7 seen[n] = copy
8 for nb in n.neighbors:
9 copy.neighbors.append(dfs(nb))
10 return copy
11 return dfs(node)
Variables
node=1
cloned=1

How to think about it

  1. Create the copy BEFORE recursing to its neighbors (prevents cycles).
  2. Map lookups make the neighbor hookup O(1).
  3. BFS variant is equivalent; same O(V+E) cost.

Edge cases to catch in interview

  • Null input -> null.
  • Disconnected graph: only clone the reachable component.

Examples

Example 1cloned 4 nodes
{"adj":[[1,3],[0,2],[1,3],[0,2]],"start":0}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed