5. Graphs & Dynamic Programming
Practice Lab 2: Trees, Shortest Grid Path & Dynamic Programming
Solve three classic senior interview problems in the live Python sandbox: Lowest Common Ancestor / Path Sum, Shortest Path in a Binary Grid (BFS), and Climbing Stairs with Costs (DP).
- Check root-to-leaf target sums recursively on binary trees
- Find shortest grid paths cleanly with BFS and a visited set
- Solve 1D minimum-cost path problems with O(1)-space Dynamic Programming
Put Modules 4 and 5 together in this coding interview lab! Each drill targets a distinct core paradigm—recursive tree DFS, unweighted shortest-path grid BFS, and O(1)-space 1D Dynamic Programming.
Blueprint & Edge-Case Guide Before You Code
| Drill | Paradigm | Target Complexity | Classic Bug to Avoid |
|---|---|---|---|
1. has_path_sum | Binary Tree DFS | O(n) time, O(h) stack | Returning True at a non-leaf node that only has one child! |
2. shortest_grid_path | Grid BFS (deque) | O(R · C) time & space | Forgetting to check if start (0, 0) or goal (R-1, C-1) is a wall (1)! |
3. min_cost_stairs | Bottom-Up 1D DP | O(n) time, O(1) space | Off-by-one at the top step (you must step past the last index, taking min(a, b))! |
Walkthrough Notes for Each Drill
- Drill 1 (
has_path_sum):- A leaf has neither left nor right child (
not root.left and not root.right). Only at a leaf should you checktarget == root.val. - Note: Node values can be negative, so do not prune early when
rem < 0!
- A leaf has neither left nor right child (
- Drill 2 (
shortest_grid_path):- Start at
(0, 0)with path cell count1, marking(0, 0)invisitedimmediately! - Guard
1 × 1grids ([[0]]returns1,[[1]]returns-1) and blocked start/end cells upfront. - Trace on
[[0, 0, 0], [1, 1, 0], [0, 0, 0]]:(0,0):1→(0,1):2→(0,2):3→(1,2):4→(2,2):5→ returns5!
- Start at
- Drill 3 (
min_cost_stairs):- You can start at index
0or index1for free, and paycost[i]whenever you step from indexi(moving+1or+2). - Trace on
cost = [10, 15, 20](a = 0, b = 0):c = 10:a, b = 0, 10 + min(0, 0) = 10c = 15:a, b = 10, 15 + min(0, 10) = 15c = 20:a, b = 15, 20 + min(10, 15) = 30- Past the top:
min(a, b) = min(15, 30) = 15!
- You can start at index
If a root 1 has a left child 2 and right is None, calling has_path_sum(root.right, 0) on None with if not root: return target == 0 would falsely say True for target = 1—even though 1 is NOT a leaf! Always check if not root: return False, and test target == root.val only when not root.left and not root.right.
Storing (r, c, dist) inside the deque keeps shortest_grid_path concise and removes the need for a separate level-size inner loop.
Live Coding Lab
Implement all three functions in the sandbox below and uncomment the automated assert checks to verify your solutions:
Click “Run Code” to execute this snippet right in your browser.
Lab Checkpoint
In has_path_sum(TreeNode(1, TreeNode(2)), 1), why must the function return False?