Compute time to burn tree
Company: Tesla
Role: Backend Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency with tree algorithms, distance computation, and propagation modeling, testing the ability to reason about how a process spreads across parent-child relationships in a tree.
Constraints
- `1 <= len(tree) <= 10^5`
- `tree[0]` is not `None`
- Each entry in `tree` is either an integer or `None`
- All non-`None` node values are unique
- `target` is guaranteed to be one of the non-`None` values in `tree`
Examples
Input: ([1, 2, 3, 4, 5, None, 6], 5)
Expected Output: 4
Explanation: The longest path from node 5 is 5 -> 2 -> 1 -> 3 -> 6, which has 4 edges, so the tree finishes burning in 4 minutes.
Input: ([7], 7)
Expected Output: 0
Explanation: There is only one node, and it is already burning at time 0.
Input: ([1, 2, None, 3, None, None, None, 4], 3)
Expected Output: 2
Explanation: This forms a chain 1 -> 2 -> 3 -> 4. Starting from 3, the farthest node is 1, two edges away.
Input: ([10, 5, 15, 2, 7, 12, 20, None, None, 6, 8], 10)
Expected Output: 3
Explanation: Starting from the root 10, the deepest nodes 6 and 8 are 3 edges away, so the full burn time is 3.
Input: ([1, 2, 3, None, 4, None, None, None, None, 5], 5)
Expected Output: 4
Explanation: The farthest node from 5 is 3 along the path 5 -> 4 -> 2 -> 1 -> 3, which takes 4 minutes.
Input: ([0, -2, 5, -3, -1, None, 9], -2)
Expected Output: 3
Explanation: From -2, the farthest node is 9 along the path -2 -> 0 -> 5 -> 9, so the answer is 3.
Hints
- If you can move from a node to its parent as well as its children, the tree behaves like an undirected graph.
- Build the parent/adjacency relationships first, then run BFS from the target one minute at a time to find the farthest reachable node.