Amazon Interview Question

Made a "deep copy" function for the following class: public class Node { public String data; public List<Node> chain; } By "deep copy" he meant that each node in the chain needs to be a fresh copy, not the original nodes. That way modifying the original node will not change the copy in any way.

Interview Answer

Anonymous

Mar 5, 2013

The key problem is that you could have a never-ending copying loop. Say you're trying to copy node A and node A is in A.chain. If you just recursively call your copy function, you'll end up recursing forever. You want to use a hash table, with the original nodes as keys that point to their new copy. That way you only end up creating a new node when you need to.

4