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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
This is hard problem, if we don’t know Union Find data structure, as this problem is modelled on Union Find. Look at some medium problems like Redundant Connection OR Number of Provinces before solving this problem, and understand Union Find data structure.
Method 1 - Using Union Find
The concept is to start with an empty graph for both Alice and Bob and incrementally add edges to make the graph connected.
Union-Find provides a simple solution by initially considering all nodes as separate components and merging them as edges are added.
Since some edges cater exclusively to Bob and others to Alice, we’ll use two separate Union-Find structures to manage their respective connections.
It’s crucial to prioritize type 3 edges over type 1 and type 2 edges since type 3 edges benefit both Bob and Alice simultaneously.
Steps
- Sort the edges based on type, in reverse order as we prefer type-3 edge, which allows both Alice and Bob to traverse.
- Now, build the union-find graph for both alice and bob.
- If we add the edge to either Alice and Bob, when doing
union
operation, we countaddedEdges
- If we add the edge to either Alice and Bob, when doing
- In the end, we check both alice and bob are fully connected, and return the difference between
edges.length
andaddedEdges
.
Code
|
|
Complexity
- Time:
O(m log m + mα(n))
, wherem
is number of edges, andn
is number nodes.- As we sorted the edges, it takes
O(m log m)
- Adding an edge using union operation takes
O(α(n))
, where α(n) is the extremely fast inverse Ackermann function. - As we are adding
m
edges, it takesO(mα(n))
- As we sorted the edges, it takes
- Space:
O(n)
, wheren
is number of nodes as we storeparent
andrank
arrays in Union Find data structure.