Approach
Disjoint set union
For Couples Holding Hands, the implementation maintains connected components and merges them as relationships are processed.
- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 53 lines of Java from the credited upstream file 765.java.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.