← Google bank

Google · Question 64 · Graphs

Clone Graph

GraphsPythoncode⏱ O(V+E)💾 O(V)
Product-based

Problem

Clone an undirected graph represented as adjacency list.

Approach

Use DFS with hashmap to copy nodes and neighbors.

Time O(V+E)Space O(V)

How it works

  1. 1Use DFS to visit each node.
  2. 2Store clones in a hashmap to avoid duplicates.
  3. 3Recursively clone neighbours.
  4. 4Return the cloned graph root.

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; no repeated edges or self-loops.

Solution — read it, then walk it

Time O(V+E)Space O(V)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 dfs(n)if n in visitedRETURN visited[n]copy = Node(n.val)visited[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