Question presented to candidate: "You get a reference to one node of a connected, undirected graph. Each node has a value and a list of its neighbours. Return a deep copy of the whole graph β every node must be a new object, wired up the same way. Please write it in Python and tell me the complexity."
What a strong answer should cover:
- A traversal (BFS with a queue or DFS with recursion) plus a
dictmapping each original node β its copy; the map is both the visited set and the way to find the copy of a neighbour. - Why the map is mandatory: graphs have cycles, so copying without it loops forever (or duplicates nodes).
- Inserting the copy into the map before visiting its neighbours, and handling the empty input (
None). - O(V + E) time and O(V) extra space for the map and the queue (or the recursion stack).
- Python specifics:
collections.dequewithpopleft()for the queue (notlist.pop(0)), node objects are hashable by identity unless the class defines__eq__without__hash__, and recursive DFS hits the default recursion limit of 1000 on a long path.
Clarifying questions expected:
- Is the input possibly
None, and is everything reachable from the given node? - How big can the graph be (is recursion safe)?
Code / implementation expected: Yes β a clone_graph(node) function in Python using BFS or DFS with a dict, plus a check that the copy shares no node with the original.