Remove Max Number of Edges to Keep Graph Fully Traversable
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Remove Max Number of Edges to Keep Graph Fully Traversable
Alice and Bob can traverse a graph. There are three types of edges:
- Type 1: Only Alice can traverse.
- Type 2: Only Bob can traverse.
- Type 3: Both can traverse. Return the maximum number of edges you can remove such that both can traverse the entire graph.
Strategy
- Prioritize Type 3 edges: Using one Type 3 edge replaces one Type 1 AND one Type 2 edge.
- Use two DSU instances:
dsuAliceanddsuBob. - After using all potential Type 3 edges, use Type 1 for Alice and Type 2 for Bob.
- If either graph is not connected (components > 1), return -1.
Examples
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
Output: 2
Approach 1
Level II: BFS (Exhaustive Connectivity)
Intuition
Try removing each edge one by one. After removal, check if both Alice and Bob can still traverse the entire graph using two separate BFS/DFS calls. This is the brute-force way to see which edges are truly redundant.
⏱ O(E \cdot (V + E)).💾 O(V + E).
Approach 2
Level III: Two Union-Finds + Greedy Edge Selection
Intuition
Greedily add common edges (Type 3) first. Then add person-specific edges only if needed for connectivity.
⏱ O(E \cdot \alpha(V)).💾 O(V).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.