Facebook Pixel

Number of Connected Components

Prereq: DSU Set Size

Given n nodes labeled 0 through n - 1, all starting disconnected, process a list of connections that pairwise link nodes. After each connection, report the current number of connected components in the graph. A connected component is a set of nodes where any two are joined by some path of edges.

Example

Input: n = 5, connections = [[1, 2], [2, 3], [1, 3], [0, 4], [0, 4]]
Output: [4, 3, 3, 2, 2]
Explanation:

At each step, we maintain the number of connected components in the graph. Initially, there are 5 components. Edge [1, 2] merges the components containing 1 and 2, reducing the count to 4. Edge [2, 3] merges the components containing 2 and 3, reducing the count to 3. Edge [1, 3] connects nodes that are already in the same component, so the count remains 3. Edge [0, 4] merges the components containing 0 and 4, reducing the count to 2. Edge [0, 4] is a duplicate, so the count remains 2.

Try it yourself

Solution

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro