Python 3 | Union find solution (BEATS 99% for memory) with comments
class Solution:
    def minimumCost(self, n: int, connections: List[List[int]]) -> int:
        
        # least amount of edges needed to connect n nodes
        if n-1 > len(connections):
            return -1
        
        # implement find
        def find(x):
            while x != parent[x]:
                x = find(parent[x])
            return x
        
        # implement union
        def union(x,y):
            x_find = find(x)
            y_find = find(y)
            
            parent[x_find] = y_find
        
        # sort the connections according to the lowest costs
        connections.sort(key = lambda x: x[2])
        
        # define the parent node
        parent = [i for i in range(n+1)]
        ans = 0
        
        # for each connection, if they don't have the same parent, union them and add cost
        for first, second, cost in connections:
            
            # if they don't have the same parent, add the edge
            if find(first) != find(second):
                union(first,second)
                ans += cost
        
        return ans if len(set(find(x) for x in range(n+1))) == 2 else -1
Comments (0)