1579. Remove Max Number of Edges to Keep Graph Fully Traversable - Explanation

Problem Link



1. Disjoint Set Union

class DSU:
    def __init__(self, n):
        self.n = n
        self.Parent = list(range(n + 1))
        self.Size = [1] * (n + 1)

    def find(self, node):
        if self.Parent[node] != node:
            self.Parent[node] = self.find(self.Parent[node])
        return self.Parent[node]

    def union(self, u, v):
        pu = self.find(u)
        pv = self.find(v)
        if pu == pv:
            return 0
        if self.Size[pu] < self.Size[pv]:
            pu, pv = pv, pu
        self.Size[pu] += self.Size[pv]
        self.Parent[pv] = pu
        self.n -= 1
        return 1

    def isConnected(self):
        return self.n == 1

class Solution:
    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
        alice, bob = DSU(n), DSU(n)
        cnt = 0

        for type, src, dst in edges:
            if type == 3:
                cnt += (alice.union(src, dst) | bob.union(src, dst))

        for type, src, dst in edges:
            if type == 1:
                cnt += alice.union(src, dst)
            elif type == 2:
                cnt += bob.union(src, dst)

        if alice.isConnected() and bob.isConnected():
            return len(edges) - cnt
        return -1

Time & Space Complexity

  • Time complexity: O(Eα(V))O(E * α(V))
  • Space complexity: O(V)O(V)

Where VV is the number of verticies and EE is the number of edges.