Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Alice and Bob have an undirected graph of n nodes and three types of edges:
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.
Example 1:
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]] Output: 2 Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.
Example 2:
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]] Output: 0 Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.
Example 3:
Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]] Output: -1 Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.
Constraints:
1 <= n <= 1051 <= edges.length <= min(105, 3 * n * (n - 1) / 2)edges[i].length == 31 <= typei <= 31 <= ui < vi <= n(typei, ui, vi) are distinct.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Union-Find
4 [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
4 [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
4 [[3,2,3],[1,1,2],[2,3,4]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1579: Remove Max Number of Edges to Keep Graph Fully Traversable
class UnionFind {
private int[] p;
private int[] size;
public int cnt;
public UnionFind(int n) {
p = new int[n];
size = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
size[i] = 1;
}
cnt = n;
}
public int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
public boolean union(int a, int b) {
int pa = find(a - 1), pb = find(b - 1);
if (pa == pb) {
return false;
}
if (size[pa] > size[pb]) {
p[pb] = pa;
size[pa] += size[pb];
} else {
p[pa] = pb;
size[pb] += size[pa];
}
--cnt;
return true;
}
}
class Solution {
public int maxNumEdgesToRemove(int n, int[][] edges) {
UnionFind ufa = new UnionFind(n);
UnionFind ufb = new UnionFind(n);
int ans = 0;
for (var e : edges) {
int t = e[0], u = e[1], v = e[2];
if (t == 3) {
if (ufa.union(u, v)) {
ufb.union(u, v);
} else {
++ans;
}
}
}
for (var e : edges) {
int t = e[0], u = e[1], v = e[2];
if (t == 1 && !ufa.union(u, v)) {
++ans;
}
if (t == 2 && !ufb.union(u, v)) {
++ans;
}
}
return ufa.cnt == 1 && ufb.cnt == 1 ? ans : -1;
}
}
// Accepted solution for LeetCode #1579: Remove Max Number of Edges to Keep Graph Fully Traversable
type unionFind struct {
p, size []int
cnt int
}
func newUnionFind(n int) *unionFind {
p := make([]int, n)
size := make([]int, n)
for i := range p {
p[i] = i
size[i] = 1
}
return &unionFind{p, size, n}
}
func (uf *unionFind) find(x int) int {
if uf.p[x] != x {
uf.p[x] = uf.find(uf.p[x])
}
return uf.p[x]
}
func (uf *unionFind) union(a, b int) bool {
pa, pb := uf.find(a-1), uf.find(b-1)
if pa == pb {
return false
}
if uf.size[pa] > uf.size[pb] {
uf.p[pb] = pa
uf.size[pa] += uf.size[pb]
} else {
uf.p[pa] = pb
uf.size[pb] += uf.size[pa]
}
uf.cnt--
return true
}
func maxNumEdgesToRemove(n int, edges [][]int) (ans int) {
ufa := newUnionFind(n)
ufb := newUnionFind(n)
for _, e := range edges {
t, u, v := e[0], e[1], e[2]
if t == 3 {
if ufa.union(u, v) {
ufb.union(u, v)
} else {
ans++
}
}
}
for _, e := range edges {
t, u, v := e[0], e[1], e[2]
if t == 1 && !ufa.union(u, v) {
ans++
}
if t == 2 && !ufb.union(u, v) {
ans++
}
}
if ufa.cnt == 1 && ufb.cnt == 1 {
return
}
return -1
}
# Accepted solution for LeetCode #1579: Remove Max Number of Edges to Keep Graph Fully Traversable
class UnionFind:
def __init__(self, n):
self.p = list(range(n))
self.size = [1] * n
self.cnt = n
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a, b):
pa, pb = self.find(a - 1), self.find(b - 1)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
self.cnt -= 1
return True
class Solution:
def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
ufa = UnionFind(n)
ufb = UnionFind(n)
ans = 0
for t, u, v in edges:
if t == 3:
if ufa.union(u, v):
ufb.union(u, v)
else:
ans += 1
for t, u, v in edges:
if t == 1:
ans += not ufa.union(u, v)
if t == 2:
ans += not ufb.union(u, v)
return ans if ufa.cnt == 1 and ufb.cnt == 1 else -1
// Accepted solution for LeetCode #1579: Remove Max Number of Edges to Keep Graph Fully Traversable
struct Solution;
struct UnionFind {
parent: Vec<usize>,
n: usize,
}
impl UnionFind {
fn new(n: usize) -> Self {
let parent = (0..n).collect();
UnionFind { parent, n }
}
fn find(&mut self, i: usize) -> usize {
let j = self.parent[i];
if i == j {
i
} else {
let k = self.find(j);
self.parent[i] = k;
k
}
}
fn union(&mut self, i: usize, j: usize) -> bool {
let i = self.find(i);
let j = self.find(j);
if i == j {
false
} else {
self.n -= 1;
self.parent[i] = j;
true
}
}
}
impl Solution {
fn max_num_edges_to_remove(n: i32, edges: Vec<Vec<i32>>) -> i32 {
let n = n as usize;
let m = edges.len();
let mut alice = UnionFind::new(n);
let mut bob = UnionFind::new(n);
let mut edges: Vec<(i32, usize, usize)> = edges
.into_iter()
.map(|v| (v[0], v[1] as usize - 1, v[2] as usize - 1))
.collect();
edges.sort_unstable();
let mut keep = 0;
while let Some(edge) = edges.pop() {
match edge.0 {
3 => {
let a = alice.union(edge.1, edge.2);
let b = bob.union(edge.1, edge.2);
if a || b {
keep += 1;
}
}
2 => {
if bob.union(edge.1, edge.2) {
keep += 1;
}
}
1 => {
if alice.union(edge.1, edge.2) {
keep += 1;
}
}
_ => {}
}
}
if alice.n == 1 && bob.n == 1 {
(m - keep) as i32
} else {
-1
}
}
}
#[test]
fn test() {
let n = 4;
let edges = vec_vec_i32![
[3, 1, 2],
[3, 2, 3],
[1, 1, 3],
[1, 2, 4],
[1, 1, 2],
[2, 3, 4]
];
let res = 2;
assert_eq!(Solution::max_num_edges_to_remove(n, edges), res);
let n = 4;
let edges = vec_vec_i32![[3, 1, 2], [3, 2, 3], [1, 1, 4], [2, 1, 4]];
let res = 0;
assert_eq!(Solution::max_num_edges_to_remove(n, edges), res);
let n = 4;
let edges = vec_vec_i32![[3, 2, 3], [1, 1, 2], [2, 3, 4]];
let res = -1;
assert_eq!(Solution::max_num_edges_to_remove(n, edges), res);
}
// Accepted solution for LeetCode #1579: Remove Max Number of Edges to Keep Graph Fully Traversable
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1579: Remove Max Number of Edges to Keep Graph Fully Traversable
// class UnionFind {
// private int[] p;
// private int[] size;
// public int cnt;
//
// public UnionFind(int n) {
// p = new int[n];
// size = new int[n];
// for (int i = 0; i < n; ++i) {
// p[i] = i;
// size[i] = 1;
// }
// cnt = n;
// }
//
// public int find(int x) {
// if (p[x] != x) {
// p[x] = find(p[x]);
// }
// return p[x];
// }
//
// public boolean union(int a, int b) {
// int pa = find(a - 1), pb = find(b - 1);
// if (pa == pb) {
// return false;
// }
// if (size[pa] > size[pb]) {
// p[pb] = pa;
// size[pa] += size[pb];
// } else {
// p[pa] = pb;
// size[pb] += size[pa];
// }
// --cnt;
// return true;
// }
// }
//
// class Solution {
// public int maxNumEdgesToRemove(int n, int[][] edges) {
// UnionFind ufa = new UnionFind(n);
// UnionFind ufb = new UnionFind(n);
// int ans = 0;
// for (var e : edges) {
// int t = e[0], u = e[1], v = e[2];
// if (t == 3) {
// if (ufa.union(u, v)) {
// ufb.union(u, v);
// } else {
// ++ans;
// }
// }
// }
// for (var e : edges) {
// int t = e[0], u = e[1], v = e[2];
// if (t == 1 && !ufa.union(u, v)) {
// ++ans;
// }
// if (t == 2 && !ufb.union(u, v)) {
// ++ans;
// }
// }
// return ufa.cnt == 1 && ufb.cnt == 1 ? ans : -1;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Track components with a list or adjacency matrix. Each union operation may need to update all n elements’ component labels, giving O(n) per union. For n union operations total: O(n²). Find is O(1) with direct lookup, but union dominates.
With path compression and union by rank, each find/union operation takes O(α(n)) amortized time, where α is the inverse Ackermann function — effectively constant. Space is O(n) for the parent and rank arrays. For m operations on n elements: O(m × α(n)) total.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.