mediumDSA

How do you clone a graph?

257 views
01

Understand the problem

Explain deep-copying a graph.

graphshashingbfs
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

BFS with original→clone map
Run Playground
from collections import deque

class Node:
    def __init__(self, val):
        self.val = val
        self.neighbors = []

def clone_graph(node):
    if not node:
        return None
    clones = {node: Node(node.val)}
    q = deque([node])
    while q:
        cur = q.popleft()
        for nb in cur.neighbors:
            if nb not in clones:
                clones[nb] = Node(nb.val)
                q.append(nb)
            clones[cur].neighbors.append(clones[nb])
    return clones[node]


# --- demo ---  square graph 1-2-3-4-1
a, b, c, d = Node(1), Node(2), Node(3), Node(4)
a.neighbors = [b, d]; b.neighbors = [a, c]
c.neighbors = [b, d]; d.neighbors = [a, c]
copy = clone_graph(a)
print(copy is not a)                              # True  (deep copy)
print(copy.val, [n.val for n in copy.neighbors])  # 1 [2, 4]
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.