Python short and clean. DSU (Disjoint-Set-Union). Functional programming.
Approach\nTL;DR, Similar to Editorial solution.\n\n# Complexity\n- Time complexity: O(e)\n\n- Space complexity: O(n)\n\nwhere,\nn is number of nodes,\ne is numb
# Approach\nTL;DR, Similar to [Editorial solution](https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/editorial/).\n\n# Complexity\n- Time complexity: $$O(e)$$\n\n- Space complexity: $$O(n)$$\n\nwhere,\n`n is number of nodes`,\n`e is number of edges`.\n\n# Code\n```python\nclass Solution:\n    def maxNumEdgesToRemove(self, n: int, edges: list[list[int]]) -> int:\n        es = reduce(lambda a, x: a[x[0]].append((x[1], x[2])) or a, edges, ([], [], [], []))\n\n        def union_count(dsu: DSU, es: Iterable[tuple[T, T]]) -> int:\n            return sum(dsu.union(u, v) or 1 for u, v in es if not dsu.is_connected(u, v))\n\n        xs = range(1, n + 1)\n        a_dsu, b_dsu = DSU(xs), DSU(xs)\n        used = sum((\n            union_count(a_dsu, es[3]) and\n            union_count(b_dsu, es[3]),\n            union_count(a_dsu, es[1]),\n            union_count(b_dsu, es[2]),\n        ))\n\n        return len(edges) - used if a_dsu.ds_count() == b_dsu.ds_count() == 1 else -1\n\n\nT = Hashable\n\n\nclass DSU:\n    def __init__(self, xs: Iterable[T] = ()) -> None:\n        self.parents: Mapping[T, T] = {x: x for x in xs}\n        self.sizes: Mapping[T, int] = {x: 1 for x in xs}\n        self.count: int = len(self.parents)\n\n    def find(self, u: T) -> T:\n        self.parents[u] = u if self.parents[u] == u else self.find(self.parents[u])\n        return self.parents[u]\n\n    def union(self, u: T, v: T) -> None:\n        ur, vr = self.find(u), self.find(v)\n        if ur == vr:\n            return\n        low, high = (ur, vr) if self.sizes[ur] < self.sizes[vr] else (vr, ur)\n        self.parents[low] = high\n        self.sizes[high] += self.sizes[low]\n        self.count -= 1\n\n    def is_connected(self, u: T, v: T) -> bool:\n        return self.find(u) == self.find(v)\n\n    def ds_count(self) -> int:\n        return self.count\n```
['Union Find', 'Graph', 'Python', 'Python3']