def solution(n, connections):
    parent = list(range(n))

    def find(x):
        if parent[x] != x:
            parent[x] = find(parent[x])
        return parent[x]

    def union(a, b):
        pa = find(a)
        pb = find(b)

        if pa != pb:
            parent[pb] = pa

    for a, b in connections:
        union(a, b)

    answer = set()

    for i in range(n):
        answer.add(find(i))

    return len(answer)


n = 4
connections = [[0, 1], [2, 3]]

print(solution(n, connections))

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: