Remove Max Number of Edges to Keep Graph Fully Traversable

HardGraphsunion find

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

An undirected graph has n nodes labeled 1 to n. Each edge edges[i] = [type_i, u_i, v_i] has one of three types: - Type 1: only Alice can use it. - Type 2: only Bob can use it. - Type 3: both Alice and Bob can use it. The graph is **fully traversable** by a person if, using only the edges that person may use, every node can reach every other node. Return the **maximum number of edges you can remove** so that the remaining graph is still fully traversable by both Alice and Bob. If it is not fully traversable by both even with all edges, return -1.

Examples

Input: n = 3, edges = [[3,1,2],[3,2,3],[1,1,3],[2,1,3],[1,1,2]]
Output: 3
The two shared edges already connect all three nodes for both people, so the other three edges are removable.
Input: n = 3, edges = [[1,1,2],[2,1,2],[3,2,3]]
Output: 0
Every edge is needed: Alice needs `1-2` (type 1) and Bob needs `1-2` (type 2), and both need `2-3`.
Input: n = 3, edges = [[1,1,2],[3,2,3]]
Output: -1
Bob cannot reach node 1.

Constraints

  • `2 <= n <= 10^5`
  • `1 <= edges.length <= min(10^5, 3 * n * (n - 1) / 2)`
  • `edges[i][0]` is 1, 2, or 3
  • `1 <= u_i < v_i <= n`
  • All tuples `(type_i, u_i, v_i)` are distinct

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More union find problems