Remove Max Number of Edges to Keep Graph Fully Traversable - Problem
Imagine Alice and Bob are explorers navigating a mysterious network of interconnected cities. They have a map showing n cities connected by three different types of roads:
- Type 1 roads: Only Alice can travel on these (restricted access)
- Type 2 roads: Only Bob can travel on these (different restrictions)
- Type 3 roads: Both Alice and Bob can use these (public roads)
Your mission is to remove the maximum number of roads while ensuring both explorers can still reach every city from any starting point. Think of it as optimizing the road network - keeping only the essential connections.
Given an array edges where edges[i] = [type, u, v] represents a bidirectional road of the specified type between cities u and v, return the maximum number of roads you can remove. If it's impossible for both Alice and Bob to fully traverse the network, return -1.
Input & Output
example_1.py โ Basic Connected 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:
We can remove 2 edges and keep the graph fully traversable by both Alice and Bob. The optimal solution keeps edges that form minimum spanning trees for both Alice's and Bob's graphs. Type 3 edges are prioritized since they benefit both users.
example_2.py โ Impossible Case
$
Input:
n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
โบ
Output:
-1
๐ก Note:
Bob cannot reach node 4 because there's no Type 2 or Type 3 edge connecting to node 4 that Bob can use. Only Alice can use the Type 1 edge to reach node 4, making it impossible for Bob to fully traverse the graph.
example_3.py โ Minimum Case
$
Input:
n = 2, edges = [[1,1,2],[2,1,2],[3,1,2]]
โบ
Output:
2
๐ก Note:
Only one edge is needed to connect 2 nodes. The Type 3 edge can be used by both Alice and Bob, so the two Type 1 and Type 2 edges are redundant and can be removed.
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
Inventory Assessment
Catalog all roads: shared highways (Type 3), car-only roads (Type 1), and truck-only roads (Type 2)
2
Shared Infrastructure First
Build shared highways first - they're most efficient since both vehicle types benefit
3
Fill Gaps
Add specialized roads (Type 1 for cars, Type 2 for trucks) only where needed for connectivity
4
Calculate Savings
Count essential roads, subtract from total to find how many can be closed
Key Takeaway
๐ฏ Key Insight: Shared resources (Type 3 edges) are most valuable in network optimization because they simultaneously contribute to multiple objectives, maximizing efficiency while minimizing redundancy.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code