- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 72 lines of Java from the credited upstream file 685.java.
- The implementation visibly relies on sequence storage.
- 4 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 boolean unionByRank(int u, int v) {10 final int i = find(u);11 final int j = find(v);12 if (i == j)13 return false;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 return true;23 }24 25 private int[] id;26 private int[] rank;27 28 private int find(int u) {29 return id[u] == u ? u : (id[u] = find(id[u]));30 }31}32 33class Solution {34 public int[] findRedundantDirectedConnection(int[][] edges) {35 int[] ids = new int[edges.length + 1];36 int nodeWithTwoParents = 0;37 38 for (int[] edge : edges) {39 final int v = edge[1];40 if (++ids[v] == 2) {41 nodeWithTwoParents = v;42 break;43 }44 }45 46 47 if (nodeWithTwoParents == 0)48 return findRedundantDirectedConnection(edges, -1);49 50 for (int i = edges.length - 1; i >= 0; --i)51 if (edges[i][1] == nodeWithTwoParents)52 53 if (findRedundantDirectedConnection(edges, i).length == 0)54 return edges[i];55 56 throw new IllegalArgumentException();57 }58 59 private int[] findRedundantDirectedConnection(int[][] edges, int skippedEdgeIndex) {60 UnionFind uf = new UnionFind(edges.length + 1);61 62 for (int i = 0; i < edges.length; ++i) {63 if (i == skippedEdgeIndex)64 continue;65 if (!uf.unionByRank(edges[i][0], edges[i][1]))66 return edges[i];67 }68 69 return new int[] {};70 }71}72