Funcia
Lv.2graphunion-find

Friend Network Groups

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
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

nlinksresult
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

  • 1≤1 \le n ≤100,000\le 100{,}000, 1≤1 \le links.length ≤200,000\le 200{,}000
  • 0≤a,b<n0 \le a, b < n; self links and repeated links may appear.

Expected complexity

Time
O((N + M) α(N))
Space
O(N)

Examples

nlinksExpected
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 O(M(N+M))O(M(N + M)) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251656 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample02inputs and outputs
correctness409verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.