class Solution:

    def to_graph(self, edges):
        graph = defaultdict(list)
        for a, b in edges:
            graph[b].append(a)  # directed graph { node: [parents] }
        return graph

    def dfs(self, v, graph, visited, path=list()):
        visited.add(v)
        for nxt in graph[v]:
            path.append(nxt)
            if nxt not in visited:
                return self.dfs(nxt, graph, visited, path)
            else:
                return path
                # cycle
        return False

    def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
        graph = self.to_graph(edges)
        visited = set()

        has_two_parents = [(node, parents) for node, parents in list(graph.items()) if len(parents) == 2]

        if len(has_two_parents) > 0:
            node, parents = has_two_parents[0]
            parent1, parent2 = parents

            graph[node] = [parent1]
            if self.dfs(node, graph, visited):
                return [parent1, node]
            else:
                return [parent2, node]

        path = list()
        self.dfs(edges[0][0], graph, visited, path)

        for a, b in edges[::-1]:
            if a in path and b in path:
                return [a, b]
