- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 77 lines of Java from the credited upstream file 2092.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 6 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.
Use this to learn the idea, then write your own version.
1class UnionFind {2 public UnionFind(int n) {3 id = new int[n];4 rank = new int[n];5 for (int i = 0; i < n; ++i)6 id[i] = i;7 }8 9 public void unionByRank(int u, int v) {10 final int i = find(u);11 final int j = find(v);12 if (i == j)13 return;14 if (rank[i] < rank[j]) {15 id[i] = j;16 } else if (rank[i] > rank[j]) {17 id[j] = i;18 } else {19 id[i] = j;20 ++rank[j];21 }22 }23 24 public boolean connected(int u, int v) {25 return find(u) == find(v);26 }27 28 public void reset(int u) {29 id[u] = u;30 }31 32 private int[] id;33 private int[] rank;34 35 private int find(int u) {36 return id[u] == u ? u : (id[u] = find(id[u]));37 }38}39 40class Solution {41 public List<Integer> findAllPeople(int n, int[][] meetings, int firstPerson) {42 List<Integer> ans = new ArrayList<>();43 UnionFind uf = new UnionFind(n);44 TreeMap<Integer, List<Pair<Integer, Integer>>> timeToPairs = new TreeMap<>();45 46 uf.unionByRank(0, firstPerson);47 48 for (int[] meeting : meetings) {49 final int x = meeting[0];50 final int y = meeting[1];51 final int time = meeting[2];52 timeToPairs.putIfAbsent(time, new ArrayList<>());53 timeToPairs.get(time).add(new Pair<>(x, y));54 }55 56 for (List<Pair<Integer, Integer>> pairs : timeToPairs.values()) {57 Set<Integer> peopleUnioned = new HashSet<>();58 for (Pair<Integer, Integer> pair : pairs) {59 final int x = pair.getKey();60 final int y = pair.getValue();61 uf.unionByRank(x, y);62 peopleUnioned.add(x);63 peopleUnioned.add(y);64 }65 for (final int person : peopleUnioned)66 if (!uf.connected(person, 0))67 uf.reset(person);68 }69 70 for (int i = 0; i < n; ++i)71 if (uf.connected(i, 0))72 ans.add(i);73 74 return ans;75 }76}77