#1579
Hard Algorithms Remove max number of edges to keep graph fully traversable
Union-Find Graph Theory
70.2% acceptance
Feb 25, 2026
2678
46
Alice and Bob have an undirected graph of n nodes and three types of edges:
Type 1: Can be traversed by Alice only.
Type 2: Can be traversed by Bob only.
Type 3: Can be traversed by both Alice and Bob.
Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.
Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn max_num_edges_to_remove(n: i32, edges: Vec<Vec<i32>>) -> i32 {
let n = n as usize;
// Union-Find
struct UF {
parent: Vec<usize>,
rank: Vec<usize>,
components: usize,
}
impl UF {
fn new(n: usize) -> Self {
UF {
parent: (0..=n).collect(),
rank: vec![0; n + 1],
components: n,
}
}
fn find(&mut self, x: usize) -> usize {
if self.parent[x] != x {
self.parent[x] = self.find(self.parent[x]);
}
self.parent[x]
}
fn union(&mut self, x: usize, y: usize) -> bool {
let rx = self.find(x);
let ry = self.find(y);
if rx == ry {
return false;
}
if self.rank[rx] < self.rank[ry] {
self.parent[rx] = ry;
} else if self.rank[rx] > self.rank[ry] {
self.parent[ry] = rx;
} else {
self.parent[ry] = rx;
self.rank[rx] += 1;
}
self.components -= 1;
true
}
}
let mut uf_a = UF::new(n);
let mut uf_b = UF::new(n);
let mut removed = 0;
// Process type 3 edges first (shared)
for e in &edges {
if e[0] == 3 {
let u = e[1] as usize;
let v = e[2] as usize;
let used_a = uf_a.union(u, v);
let used_b = uf_b.union(u, v);
if !used_a && !used_b {
removed += 1;
}
}
}
// Process type 1 (Alice) and type 2 (Bob)
for e in &edges {
let u = e[1] as usize;
let v = e[2] as usize;
if e[0] == 1 {
if !uf_a.union(u, v) {
removed += 1;
}
} else if e[0] == 2 {
if !uf_b.union(u, v) {
removed += 1;
}
}
}
// Check full connectivity
if uf_a.components != 1 || uf_b.components != 1 {
return -1;
}
removed
}
}