SDE & MLE Prep

685. Redundant Connection II

Asked at 1Google21

Problem

A rooted tree (edges point from parent to child, every node except the root has exactly one parent) on nodes 1…n got one extra directed edge. Given the edges, return an edge whose removal leaves a rooted tree; if several qualify, return the one that appears last in the input.

Example: [[1,2],[1,3],[2,3]] → [2,3]; [[1,2],[2,3],[3,4],[4,1],[1,5]] → [4,1]

A rooted tree plus one extra directed edge creates either (a) a node with two parents, (b) a cycle, or both. If some node has two parents, the answer is one of those two edges: skip the later one and check with Union-Find whether a cycle remains — if yes, the earlier edge is the culprit. Otherwise return the edge that closes the cycle.

Complexity: O(n · α(n)).

class Solution:
    def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
        n = len(edges)
        parent_of, cand1, cand2 = {}, None, None
        for u, v in edges:
            if v in parent_of:
                cand1, cand2 = [parent_of[v], v], [u, v]
            else:
                parent_of[v] = u
        root = list(range(n + 1))

        def find(x):
            while root[x] != x:
                root[x] = root[root[x]]
                x = root[x]
            return x

        for u, v in edges:
            if [u, v] == cand2:
                continue
            ru, rv = find(u), find(v)
            if ru == rv:                       # cycle found
                return cand1 if cand1 else [u, v]
            root[rv] = ru
        return cand2