← Meta (Facebook) bank

Meta (Facebook) · Question 59 · Graphs

Clone Graph

GraphsPythoncode⏱ O(n+e)💾 O(n)
Product-based

Problem

You are given reference of node in connected undirected graph. Return deep copy.

Approach

DFS-clone each node once, memoizing copies in a hashmap.

Time O(n+e)Space O(n)

How it works

  1. 1Clone nodes on first DFS visit.
  2. 2Memoize to preserve sharing and cycles.

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; connected undirected graph.

Solution — read it, then walk it

Time O(n+e)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 Nonevisited = {}DEFINE clone(node)if node in visitedRETURN visited[node]copy = Node(node.val)visited[node] = copyfor neighbor innode.neighborscopy.neighbors.append(clone(neighbor))RETURN copyRETURN clone(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