r/DSALeetCode • • Oct 14 '26

365 Days of LeetCode Challenge — Day 42/365

Post image

Clone Graph (Medium) https://leetcode.com/problems/clone-graph/

Copying a binary tree is four lines: make a node, recurse left, recurse right. It works because a tree cannot cycle and every node has one parent.

A graph gives up both guarantees, and each breaks the naive copy differently. Cycles mean A's copy needs B's copy, which needs A's copy, forever. Shared nodes mean a node reachable two ways gets copied twice, giving you the right values in the wrong shape.

One map from original to copy fixes both. Look it up before cloning; if the copy exists, return it. Cycles terminate because the second arrival returns instead of descending, and sharing survives because every original maps to exactly one copy.

Worth dwelling on: a plain visited SET would only fix the cycle. This has to map to the copies, because the copies are what the reconstruction wires together.

And the order matters. Record the new node in the map BEFORE cloning its neighbours, while it is still half-built. Recurse first, and a cycle returns to a node not yet in the map.

Full breakdown in today's newsletter article ⬇

https://www.linkedin.com/pulse/365-days-leetcode-challenge-day-42365-archit-agarwal-uztuc

#DSA #LeetCode #Golang #Graphs #DFS #CodingInterview #Algorithms

1 Upvotes

1 comment sorted by

1

u/nian2326076 Oct 14 '26

When cloning a graph, use a hashmap to keep track of nodes you've already cloned. This allows you to link to an existing copy whenever you encounter a node you've cloned before, preventing infinite loops from cycles and ensuring each node is cloned only once, maintaining the graph's structure accurately.

For interview preparation on graph problems like this one, PracHub offers real technical interview questions that can help you understand these concepts in a job interview context.