Advertisement
1988coder

684. Redundant Connection

Dec 30th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1. /**
  2.  * Using union-find by rank and path compression.
  3.  *
  4.  * Time Complexity Calculations: Total Number of operations=(N). Number of
  5.  * nodes=N Thus time complexity=O(N * alpha(N)) alpha(N) (Also know as
  6.  * Inverse-Ackermann function) grows very slowly and will always be less than or
  7.  * equal to 4.
  8.  *
  9.  * Time Complexity: O(N) Space Complexity : O(N)
  10.  *
  11.  * N = number of edges or the length of edges array.
  12.  */
  13. class Solution {
  14.     public int[] findRedundantConnection(int[][] edges) throws IllegalArgumentException {
  15.         if (edges == null) {
  16.             throw new IllegalArgumentException("Input edges array is null");
  17.         }
  18.         if (edges.length == 0 || edges[0].length == 0) {
  19.             return null;
  20.         }
  21.  
  22.         UnionFind dsu = new UnionFind(edges.length);
  23.         for (int[] edge : edges) {
  24.             if (!dsu.union(edge[0], edge[1])) {
  25.                 return edge;
  26.             }
  27.         }
  28.         return null;
  29.     }
  30.  
  31.     class UnionFind {
  32.         int[] parent;
  33.         int[] rank;
  34.  
  35.         UnionFind(int n) {
  36.             parent = new int[n + 1];
  37.             rank = new int[n + 1];
  38.             for (int i = 1; i <= n; i++) {
  39.                 parent[i] = i;
  40.             }
  41.         }
  42.  
  43.         public int findSet(int x) {
  44.             if (x != parent[x]) {
  45.                 parent[x] = findSet(parent[x]);
  46.             }
  47.             return parent[x];
  48.         }
  49.  
  50.         public boolean union(int x, int y) {
  51.             int parentX = findSet(x);
  52.             int parentY = findSet(y);
  53.  
  54.             if (parentX == parentY) {
  55.                 return false;
  56.             }
  57.  
  58.             if (rank[parentX] >= rank[parentY]) {
  59.                 rank[parentX] = rank[parentX] == rank[parentY] ? rank[parentX] + 1 : rank[parentX];
  60.                 parent[parentY] = parentX;
  61.             } else {
  62.                 parent[parentX] = parentY;
  63.             }
  64.  
  65.             return true;
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement