Clone Graph
MediumThis is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.
Question
You're maintaining a web of contacts. Every contact has a unique id and a list of the other contacts it's directly linked with (a link always goes both ways).
You're handed one contact from this web. Build a separate copy of every contact you can reach from it. Use brand new contact objects. Link the same ids together the same way the original does. Your copy can't reuse a single object from the original. That way, editing your copy never changes the original web.
Input: web = {1: [2], 2: [1]}, start = 1
Output: an independent web shaped like {1: [2], 2: [1]}
Here, two contacts are linked to each other. Your copy has two brand new contact objects that are linked the same way.
Input: web = {1: [2, 3], 2: [1, 3], 3: [1, 2]}, start = 1
Output: an independent web shaped like the original, starting from a copy of contact 1
Here, all three contacts are linked to each other. If you follow the links from contact 1, you eventually end up back at contact 1. That means your traversal has to avoid looping forever.
Input: web = {1: []}, start = 1
Output: a single, separate contact with no links
A contact with no links still needs its own fresh copy.
Clarify the problem
What are some questions you'd ask an interviewer?
Understand the problem
Remember to understand the problem and plan your approach before you start coding.