LeetCodee

685. Redundant Connection II

Jump to Solution: Python Java C++ JavaScript C#

Problem Description

In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.

The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed.

The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent of child vi.

Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.

Examples:

Example 1:

Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]

Example 2:

Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
Output: [4,1]

Constraints:

  • n == edges.length
  • 3 ≤ n ≤ 1000
  • edges[i].length == 2
  • 1 ≤ ui, vi ≤ n
  • ui != vi

Python Solution

class Solution:
    def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
        n = len(edges)
        parent = list(range(n + 1))
        
        def find(x):
            if parent[x] != x:
                parent[x] = find(parent[x])
            return parent[x]
        
        def union(x, y):
            parent[find(x)] = find(y)
            
        # Check for node with two parents
        indegree = [0] * (n + 1)
        for u, v in edges:
            indegree[v] += 1
            
        candidates = []
        for i, (u, v) in enumerate(edges):
            if indegree[v] == 2:
                candidates.append(i)
                
        if candidates:
            # Try removing each candidate edge
            edges_to_try = edges[:candidates[0]] + edges[candidates[0]+1:]
            parent = list(range(n + 1))
            
            valid = True
            for u, v in edges_to_try:
                if find(u) == find(v):
                    valid = False
                    break
                union(u, v)
                
            if valid:
                return edges[candidates[0]]
            return edges[candidates[1]]
            
        # No node has two parents, must be a cycle
        parent = list(range(n + 1))
        for u, v in edges:
            if find(u) == find(v):
                return [u, v]
            union(u, v)
            
        return []

Implementation Notes:

  • Uses Union-Find data structure with path compression
  • Handles two cases: node with two parents and cycle in graph
  • Time complexity: O(N)
  • Space complexity: O(N)

Java Solution

class Solution {
    private int[] parent;
    
    public int[] findRedundantDirectedConnection(int[][] edges) {
        int n = edges.length;
        int[] indegree = new int[n + 1];
        List candidates = new ArrayList<>();
        
        // Find nodes with two parents
        for (int[] edge : edges) {
            indegree[edge[1]]++;
            if (indegree[edge[1]] == 2) {
                candidates.add(edge[1]);
            }
        }
        
        if (!candidates.isEmpty()) {
            // Try removing each candidate edge
            int target = candidates.get(0);
            int[] lastEdge = null;
            
            for (int[] edge : edges) {
                if (edge[1] == target) {
                    if (lastEdge == null) {
                        lastEdge = edge;
                    } else {
                        parent = new int[n + 1];
                        for (int i = 0; i <= n; i++) parent[i] = i;
                        
                        boolean valid = true;
                        for (int[] e : edges) {
                            if (e == edge) continue;
                            if (find(e[0]) == find(e[1])) {
                                valid = false;
                                break;
                            }
                            union(e[0], e[1]);
                        }
                        
                        if (valid) return edge;
                        return lastEdge;
                    }
                }
            }
        }
        
        // No node has two parents, must be a cycle
        parent = new int[n + 1];
        for (int i = 0; i <= n; i++) parent[i] = i;
        
        for (int[] edge : edges) {
            if (find(edge[0]) == find(edge[1])) {
                return edge;
            }
            union(edge[0], edge[1]);
        }
        
        return new int[]{};
    }
    
    private int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
    
    private void union(int x, int y) {
        parent[find(x)] = find(y);
    }
}

C++ Solution

class Solution {
private:
    vector parent;
    
    int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
    
    void union_set(int x, int y) {
        parent[find(x)] = find(y);
    }
    
public:
    vector findRedundantDirectedConnection(vector>& edges) {
        int n = edges.size();
        vector indegree(n + 1, 0);
        vector candidates;
        
        // Find nodes with two parents
        for (const auto& edge : edges) {
            indegree[edge[1]]++;
            if (indegree[edge[1]] == 2) {
                candidates.push_back(edge[1]);
            }
        }
        
        if (!candidates.empty()) {
            // Try removing each candidate edge
            int target = candidates[0];
            vector lastEdge;
            
            for (const auto& edge : edges) {
                if (edge[1] == target) {
                    if (lastEdge.empty()) {
                        lastEdge = edge;
                    } else {
                        parent.resize(n + 1);
                        for (int i = 0; i <= n; i++) parent[i] = i;
                        
                        bool valid = true;
                        for (const auto& e : edges) {
                            if (e == edge) continue;
                            if (find(e[0]) == find(e[1])) {
                                valid = false;
                                break;
                            }
                            union_set(e[0], e[1]);
                        }
                        
                        if (valid) return edge;
                        return lastEdge;
                    }
                }
            }
        }
        
        // No node has two parents, must be a cycle
        parent.resize(n + 1);
        for (int i = 0; i <= n; i++) parent[i] = i;
        
        for (const auto& edge : edges) {
            if (find(edge[0]) == find(edge[1])) {
                return edge;
            }
            union_set(edge[0], edge[1]);
        }
        
        return {};
    }
};

JavaScript Solution

/**
 * @param {number[][]} edges
 * @return {number[]}
 */
var findRedundantDirectedConnection = function(edges) {
    const n = edges.length;
    const parent = Array.from({length: n + 1}, (_, i) => i);
    const indegree = Array(n + 1).fill(0);
    
    const find = (x) => {
        if (parent[x] !== x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    };
    
    const union = (x, y) => {
        parent[find(x)] = find(y);
    };
    
    // Find nodes with two parents
    for (const [_, v] of edges) {
        indegree[v]++;
    }
    
    const candidates = [];
    for (let i = 0; i < edges.length; i++) {
        if (indegree[edges[i][1]] === 2) {
            candidates.push(i);
        }
    }
    
    if (candidates.length > 0) {
        // Try removing each candidate edge
        const edgesToTry = [...edges.slice(0, candidates[0]), ...edges.slice(candidates[0] + 1)];
        for (let i = 0; i <= n; i++) parent[i] = i;
        
        let valid = true;
        for (const [u, v] of edgesToTry) {
            if (find(u) === find(v)) {
                valid = false;
                break;
            }
            union(u, v);
        }
        
        if (valid) return edges[candidates[0]];
        return edges[candidates[1]];
    }
    
    // No node has two parents, must be a cycle
    for (let i = 0; i <= n; i++) parent[i] = i;
    
    for (const [u, v] of edges) {
        if (find(u) === find(v)) {
            return [u, v];
        }
        union(u, v);
    }
    
    return [];
};

C# Solution

public class Solution {
    private int[] parent;
    
    public int[] FindRedundantDirectedConnection(int[][] edges) {
        int n = edges.Length;
        int[] indegree = new int[n + 1];
        List candidates = new List();
        
        // Find nodes with two parents
        foreach (var edge in edges) {
            indegree[edge[1]]++;
            if (indegree[edge[1]] == 2) {
                candidates.Add(edge[1]);
            }
        }
        
        if (candidates.Count > 0) {
            // Try removing each candidate edge
            int target = candidates[0];
            int[] lastEdge = null;
            
            foreach (var edge in edges) {
                if (edge[1] == target) {
                    if (lastEdge == null) {
                        lastEdge = edge;
                    } else {
                        parent = new int[n + 1];
                        for (int i = 0; i <= n; i++) parent[i] = i;
                        
                        bool valid = true;
                        foreach (var e in edges) {
                            if (e == edge) continue;
                            if (Find(e[0]) == Find(e[1])) {
                                valid = false;
                                break;
                            }
                            Union(e[0], e[1]);
                        }
                        
                        if (valid) return edge;
                        return lastEdge;
                    }
                }
            }
        }
        
        // No node has two parents, must be a cycle
        parent = new int[n + 1];
        for (int i = 0; i <= n; i++) parent[i] = i;
        
        foreach (var edge in edges) {
            if (Find(edge[0]) == Find(edge[1])) {
                return edge;
            }
            Union(edge[0], edge[1]);
        }
        
        return new int[]{};
    }
    
    private int Find(int x) {
        if (parent[x] != x) {
            parent[x] = Find(parent[x]);
        }
        return parent[x];
    }
    
    private void Union(int x, int y) {
        parent[Find(x)] = Find(y);
    }
}

Implementation Notes:

  • Uses Union-Find data structure with path compression
  • Handles two cases: node with two parents and cycle in graph
  • Time complexity: O(N)
  • Space complexity: O(N)
  • Returns the last edge that can be removed to make a valid tree