#323
Number of Connected Components in an Undirected Graph
medium· Graphsruns: 0You have an undirected graph of n nodes labeled 0 to n - 1. You are given the integer n and an array edges where each edges[i] = [a, b] indicates an undirected edge between a and b. Return the number of connected components in the graph.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 501
class Solution:
def countComponents(
self, n: int, edges: list[list[int]]
) -> int:
parent = list(range(n))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
components = n
for a, b in edges:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
components -= 1
return components
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.