Connected components after merges

Write codeMedium20 min

Your task

You start with n isolated nodes labeled 0..n-1 and process a list of undirected merge operations [u, v]. After each operation, report the current number of connected components. Return a list of length len(ops) giving the component count after each merge in order. Merging two already-connected nodes leaves the count unchanged.

Examples

components_after_merges(n: int, ops: list[list[int]]) -> list[int]
Example 1
Inputcomponents_after_merges(5, [[0, 1], [2, 3], [1, 3], [0, 2]])
Output[4, 3, 2, 2]