Practice › Graphs
Redundant Connection
Medium · Graphs · Asked at Google, Amazon, Microsoft, Uber
A tree with n nodes had one extra edge added, so the graph now has n edges and exactly one cycle. Print an edge that can be removed to make it a tree again; if there are several, print the one that appears last in the input. Print it exactly as it was given.
Input
First line: n. Next n lines: u v.
Output
The edge u v to remove.
Constraints
- 3 ≤ n ≤ 10^5
- no repeated edges and no self-loops
Add the edges one by one to a disjoint-set union. The first edge whose two ends are already connected closes the cycle — and since every later edge is not on the cycle, it is the last removable edge in the input.
Example 1
Input
3 1 2 1 3 2 3
Output
2 3
Example 2
Input
5 1 2 2 3 3 4 1 4 1 5
Output
1 4
Hints
- Adding edges one by one, the first edge that joins two already-connected nodes closes the only cycle.
- A disjoint-set union tells you in near O(1) whether two nodes are already connected.
- Why is that edge also the last removable one in the input?
Approach
Process the edges in input order with a DSU. When an edge (u, v) has find(u) == find(v), print it. Removable edges are exactly the edges of the cycle. The cycle is complete only once all its edges are present, so the edge that completes it is the cycle edge that comes last in the input — exactly what is asked.
Complexity: O(n α(n)) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
vector<int> parent;
int find(int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
parent.resize(n + 1);
iota(parent.begin(), parent.end(), 0);
for (int i = 0; i < n; i++) {
int u, v;
cin >> u >> v;
if (find(u) == find(v)) {
cout << u << " " << v << "\n";
return 0;
}
parent[find(u)] = find(v);
}
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
parent = list(range(n + 1))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for i in range(n):
u, v = data[1 + 2 * i], data[2 + 2 * i]
if find(u) == find(v):
print(u, v)
break
parent[find(u)] = find(v)Java solution
import java.io.*;
public class Main {
static int[] parent;
static int find(int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
parent = new int[n + 1];
for (int i = 0; i <= n; i++) parent[i] = i;
for (int i = 0; i < n; i++) {
in.nextToken();
int u = (int) in.nval;
in.nextToken();
int v = (int) in.nval;
if (find(u) == find(v)) {
System.out.println(u + " " + v);
return;
}
parent[find(u)] = find(v);
}
}
}