Practice: Clone Graph
Problem: https://leetcode.com/problems/clone-graph/
Recognition reminder: this is a traversal with a twist. You walk the graph (DFS or BFS, your choice), but as you go you build a parallel graph of brand-new nodes. The one structure that makes it work is a dict mapping each original node to its clone; you consult it both to avoid cloning a node twice and to wire up neighbor links. The visited-set discipline of every graph traversal becomes “have I already created this node’s clone”.
Signature note
Write your solution as a function clone_graph(node) that takes the reference to a node of the original graph and returns the reference to the corresponding node of a deep copy. The node type is the small Node class shown in the test file (a val plus a list of neighbors). Return None when the input is None (the empty graph). A deep copy means: the returned graph has the same shape and the same vals, but every node is a new object, so no node in your result is the same object as any node in the input.
This is the course’s first design-flavored problem: there is no single number to return, only a structure to reproduce. Build the copy, then be ready to argue it is correct (right shape, right values, all-new objects).
Before you start (the five-beat rhythm)
- Your Pattern Card for this week is already written.
- Name the pattern aloud and write your approach as a plain-English comment before any code.
- Struggle floor: 25 minutes unaided. No hints, no AI, no Discuss tab.
- If stuck past the floor, ask the tutor for a hint. Six rungs, one per ask.
- Debrief in your commit message before moving to the next problem.
Your target
Fill these in yourself before you look at anyone else’s solution:
Target time complexity: ____
Target space complexity: ____
You visit every node and every edge once, and you store one map entry per node. Let that guide the two bounds.
Where your code goes
Write your solution in your own work repo (see getting-started.md), not in this folder. This folder ships only the problem spec and a provided-example test (tests/test_provided.py) so you can check the given cases locally before you submit to LeetCode’s judge. The judge is the oracle; the tutor will not confirm your answer by reading it.
The provided test is a little larger than usual because a clone is hard to check by eye: it ships a tiny Node class, a helper that builds a graph from an adjacency list, and a checker that confirms your clone matches the original in structure and uses all-new objects (different identities). Read the comments in the file so you understand exactly what is being asserted.
Debrief (paste into your commit message)
1. What pattern did this turn out to be?
2. What was the trigger phrase or input shape that should have made me reach for it?
3. What was the time and space complexity, and what would dominate at scale?
4. What edge case would have broken my first attempt?
5. What would I do differently in three days when I see this cold?