← Uber bank

Uber · Question 38 · Graphs

Clone Graph

GraphsPythoncode⏱ O(N+M)💾 O(N)
Product-based

Problem

Given a reference to a node in a connected undirected graph, return a deep copy (clone) of the graph.

Approach

Use DFS to traverse the original graph. Keep a map from original node to cloned node.

Time O(N+M)Space O(N)

How it works

  1. 1DFS each node, cloning on first visit.
  2. 2Memoize clones in a hashmap.
  3. 3Wire each clone's neighbours recursively.

Sample input / output

Input:
4
2 2 4
2 1 3
2 2 4
2 1 3
Output:
[[1, [2, 4]], [2, [1, 3]], [3, [2, 4]], [4, [1, 3]]]

Constraints

0 <= nodes <= 100; 1 <= Node.val <= 100; connected undirected graph.

Solution — read it, then walk it

Time O(N+M)Space O(N)Loops 4Branches 4Returns 4source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesno↻ repeat↻ repeat↻ repeatyesno↻ repeatyesnoSTARTCLASS NodeDEFINE __init__(self,val=0, neighbors=None)self.val = valself.neighbors = neighborsif neighbors is not Noneelse []DEFINE cloneGraph(node)if not nodeRETURN Noneold_to_new = {}DEFINE dfs(n)if n in old_to_newRETURN old_to_new[n]copy = Node(n.val)old_to_new[n] = copyfor nei in n.neighborscopy.neighbors.append(dfs(nei))RETURN copyRETURN dfs(node)DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))nodes = [Node(i + 1) for iin range(n)]for node in nodesk = int(next(it))for _ in range(k)v = int(next(it))node.neighbors.append(nodes[v- 1])clone =cloneGraph(nodes[0])seen, stack, out = set(),[clone], []while stackcur = stack.pop()if cur in seenCONTINUEseen.add(cur)out.append([cur.val,sorted(nb.val for nb incur.neighbors)])stack.extend(cur.neighbors)print(sorted(out))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/41

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits