Skip to main content
LeetCode 1579, Hard. Topics: Union-Find, Graph Theory. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 16 parametrized pytest cases, and a playground notebook:

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

Constraints

  • 1 <= n <= 10^5
  • 1 <= edges.length <= min(10^5, 3 * n * (n - 1) / 2)
  • edges[i].length == 3
  • 1 <= typei <= 3
  • 1 <= ui < vi <= n
  • All tuples (typei, ui, vi) are distinct.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026