Remove Max Number of Edges to Keep Graph Fully Traversable - Problem
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.
Input & Output
Example 1 — Basic Graph
$
Input:
n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,4],[2,3,4]]
›
Output:
2
💡 Note:
Alice needs edges connecting all nodes using type 1 and 3. Bob needs edges using type 2 and 3. The minimum spanning trees need 4 edges total (3 for connectivity + 1 extra for different requirements), so we can remove 6 - 4 = 2 edges.
Example 2 — Impossible Case
$
Input:
n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,2,3]]
›
Output:
-1
💡 Note:
Alice cannot reach node 4 from nodes 1,2,3 using type 1 and 3 edges. Bob cannot reach node 1 from other nodes using type 2 and 3 edges. Full traversal is impossible.
Example 3 — All Shared Edges
$
Input:
n = 3, edges = [[3,1,2],[3,2,3],[3,1,3]]
›
Output:
1
💡 Note:
All edges are type 3 (shared). We need only 2 edges to connect 3 nodes (minimum spanning tree), so we can remove 3 - 2 = 1 edge.
Constraints
- 1 ≤ n ≤ 105
- 1 ≤ edges.length ≤ min(105, 3 * n * (n - 1) / 2)
- edges[i].length == 3
- 1 ≤ typei ≤ 3
- 1 ≤ ui < vi ≤ n
- All tuples (typei, ui, vi) are distinct
Visualization
Tap to expand
Understanding the Visualization
1
Input Graph
Graph with 3 types of edges: Alice-only, Bob-only, and shared
2
Find Minimum
Use Union-Find to determine minimum edges needed for connectivity
3
Calculate Result
Maximum removable = Total edges - Minimum required
Key Takeaway
🎯 Key Insight: Prioritize shared edges first since they help both Alice and Bob simultaneously, then use Union-Find to track minimum spanning trees
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code