There are n companies in a market, labeled from 0 to n - 1. Some pairs of companies have merged with each other. When two companies merge, they (and all companies already merged with either of them) become a single combined company.
You are given an integer n and a 2D list mergers where mergers[i] = [a, b] means company a and company b have merged.
Return the total number of distinct companies remaining in the market after all mergers have taken place.
Function Signature
def count_merged_companies(n: int, mergers: list[list[int]]) -> int:
Rules
-
A company that never appears in
mergers
stays on its own and counts as one company.
-
A pair whose two companies already belong to the same combined company changes nothing.
-
The answer does not depend on the order of the pairs.
Constraints
-
1 <= n <= 2000
-
0 <= len(mergers) <= n * (n - 1) / 2
-
len(mergers[i]) == 2
-
0 <= a, b < n
-
a != b
-
No merger pair is repeated.
Examples
Input: n = 5, mergers = [[0, 1], [1, 2], [3, 4]]
Output: 2
Companies 0, 1 and 2 merge into one company through their shared member 1, and companies 3 and 4 merge into another. That leaves {0, 1, 2} and {3, 4}.
Input: n = 6, mergers = [[0, 1], [2, 3], [4, 5]]
Output: 3
The three pairs share no company, so they form three separate combined companies: {0, 1}, {2, 3} and {4, 5}.
Input: n = 4, mergers = [[0, 1], [1, 2], [2, 0]]
Output: 2
The first two pairs combine 0, 1 and 2. The pair [2, 0] joins two members of that same company, so nothing changes. Company 3 never merged and counts on its own, giving {0, 1, 2} and {3}.