Algo-Sim › Advanced Graphs
Redundant Connection
Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input
A tree got one extra edge. Find the edge whose removal leaves a tree (the last such edge in the input) with union-find.
Problem
A tree with nodes 1..n had one extra edge added, so the n edges now contain exactly one cycle. Return an edge you can remove to get a tree back; if several work, return the one that appears last in the input.
Constraints
- 3 ≤ n ≤ 1000
- edges.length = n, and edges[i] = [a, b] with 1 ≤ a < b ≤ n
- No repeated edges; the graph is connected
Edge cases to test
- The extra edge is the last edge
- A cycle of length 3
- The cycle includes node 1
Follow-up questions
- What if the graph is directed?
- A node may also get two parents; check that case first, then cycles (LC 685).
- Why union-find over DFS?
- Union-find finds the first edge that closes a cycle in one pass: O(E α(V)), while DFS per edge is O(E²).
Solution
Java
public int[] findRedundantConnection(int[][] edges) {
int[] parent = new int[edges.length + 1];
for (int i = 0; i < parent.length; i++) parent[i] = i;
for (int[] e : edges) {
int a = find(parent, e[0]), b = find(parent, e[1]);
if (a == b) return e;
parent[a] = b;
}
return new int[0];
}
private int find(int[] parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}Python
def find_redundant_connection(edges):
parent = list(range(len(edges) + 1))
for u, v in edges:
a, b = find(parent, u), find(parent, v)
if a == b:
return [u, v]
parent[a] = b
return []
def find(parent, x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return xC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>> &edges) {
vector<int> parent = vector<int>(int(edges.size()) + 1);
for (int i = 0; i < int(parent.size()); i++)
parent[i] = i;
for (vector<int> &e : edges) {
int a = find(parent, e[0]), b = find(parent, e[1]);
if (a == b)
return e;
parent[a] = b;
}
return vector<int>(0);
}
int find(vector<int> &parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
};
More Advanced Graphs problems
- Network Delay Time (Medium)
- Evaluate Division (Medium)
- Course Schedule II (Medium)
- Alien Dictionary (Hard)
- Number of Connected Components (Union-Find) (Medium)
- Accounts Merge (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Min Cost to Connect All Points (Medium)
- Cheapest Flights Within K Stops (Medium)
- Bellman-Ford (negative weights) (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Strongly Connected Components (Hard)
- Reconstruct Itinerary (Hard)
- Minimum Height Trees (Medium)