← Microsoft Interview Insights
This one took me a minute to even parse correctly.
First, identify the type of violation introduced by the extra edge: either a node has two parents (in-degree 2) or the graph contains a cycle (or both). Then, systematically test candidate edges to remove, ensuring the remaining graph is a valid rooted tree with exactly one root (in-degree 0) and all other nodes having in-degree 1, and no cycles. If multiple valid edges exist, return the one that appears last in the input.
Pro tip: Clarify with the interviewer whether the tree is rooted at a specific node or if any node can be the root; this affects the validity check. Also, mention that you can solve it in O(N) time by using union-find or DFS to detect cycles and in-degree violations.
Compute the in-degree of each node. If any node has in-degree 2, the extra edge is one of the two incoming edges to that node; otherwise, the extra edge creates a cycle and all nodes have in-degree 1.
If a node has in-degree 2, the two edges pointing to it are candidates. If no such node, the extra edge is part of a cycle; find the cycle and consider each edge in the cycle as a candidate.
For each candidate edge (in reverse order if multiple), remove it and check if the remaining graph is a valid rooted tree: exactly one node with in-degree 0 (root), all others in-degree 1, and no cycles (connected and acyclic).
If multiple candidates yield a valid tree, return the one that appears last in the input array. If only one works, return that.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.