← Microsoft Interview Insights
I knew union-find was involved but kept second-guessing myself on the two-case split: when a node ends up with two parents vs when there's a cycle but no double-parent.
First, identify nodes with indegree 2 (candidates for the extra edge) and detect if a cycle exists. If a cycle exists, remove the edge that breaks the cycle; otherwise, remove the last candidate edge in the input order. Use DFS or Union-Find to efficiently detect cycles and validate the tree structure.
Pro tip: Clarify the definition of a rooted tree: exactly one root with indegree 0, all other nodes indegree 1, and no cycles. Handling the 'last in input' tie-breaker correctly shows attention to detail.
Confirm that a valid rooted tree has exactly one root (indegree 0), all other nodes indegree 1, and no cycles. Note that the extra edge may create a node with indegree 2 or a cycle, or both.
Scan the edges to find any node with indegree 2. If such a node exists, the two incoming edges are candidates for removal. If no node has indegree 2, the extra edge must be part of a cycle.
Use DFS or Union-Find to check for cycles in the graph. If a cycle exists, determine which candidate edge (if any) lies on the cycle; that edge must be removed to break the cycle.
If multiple edges could be removed (e.g., both candidates break the cycle or no cycle exists), choose the one that appears last in the input order.
After removing the chosen edge, verify that the resulting graph is a valid rooted tree (single root, no cycles, all indegrees correct). Return the removed edge.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.