← Back to problems Solve on LeetCode →

Number of Provinces

LeetCode 547 • Medium • Union-Find / DFS

There are n cities. isConnected[i][j] = 1 if i and j are directly connected. Return the number of provinces (connected components).

TimeO(n² α(n))
SpaceO(n)
Step0/0
Ready
Union-Find: each city starts as its own set; union connected pairs; count distinct roots.