Lv.2graphunion-find
Friend Network Groups
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
There are n people numbered 0 to n - 1, initially with no friendships. Friendships are made one at a time in the order
of links (links[i] = [a, b]). People connected directly or through friends form one group. After each link, report the
number of groups; return the reports as an array.
Examples
| n | links | result |
|---|---|---|
5 | [[0, 1], [1, 2], [3, 4], [0, 2], [2, 4]] | [4, 3, 2, 2, 1] |
3 | [[1, 1], [0, 2]] | [3, 2] |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(n: int, links: int[][]) → int[]
Constraints
-
n,links.length - ; self links and repeated links may appear.
Expected complexity
- Time
- O((N + M) α(N))
- Space
- O(N)
Examples
| n | links | Expected |
|---|---|---|
5 | [[0,1],[1,2],[3,4],[0,2],[2,4]] | [4,3,2,2,1] |
3 | [[1,1],[0,2]] | [3,2] |
Hint
Hint
Use union–find (disjoint set union) with path compression and union by size. Start from n groups and subtract one only when
a union actually joins two different sets. Recounting with BFS after every link is and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1656 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 2 | inputs and outputs |
| correctness | 40 | 9 | verdict only |
| performance | 60 | 4 | verdict only |