Check if enough cables. Count components. Answer = components - 1.
def makeConnected(n, connections): if len(connections) < n - 1: return -1
parent = list(range(n))
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(x, y):
px, py = find(x), find(y)
if px != py:
parent[px] = py
for a, b in connections:
union(a, b)
components = sum(1 for i in range(n) if find(i) == i)
return components - 1
time, space.