Simple Union Find in Java
Before using union, go through all restrictions, and make sure they are not in the same group as the two nodes currently being connnected. \nSay, current reques
Before using union, go through all restrictions, and make sure they are not in the same group as the two nodes currently being connnected. \nSay, current request is n1 - n2. \nAnd there is a restriction s1 - s2 \nIf s1 is connected to n1 and s2 is connected to n2. \nWhen n1 and n2 are connected, s1 and s2 get connected indirectly too. \nTherefore we make sure that there is no pair of restriction that gets connected on accepting the request. \nIf there is no pair of restriction for the same, then we do union. \n\n```\n\nclass Solution {\n    public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) {\n        int[] parent = new int[n];\n        boolean[] ans = new boolean[requests.length];\n        int[] rank = new int[requests.length];\n        for (int i = 0; i < n; i++){parent[i] = i;} \n        \n        for (int i = 0; i < requests.length; i++){\n           int t1 = find(parent, requests[i][0]);\n           int t2 = find(parent, requests[i][1]);\n           boolean vis = true;\n            for (int j = 0; j < restrictions.length; j++){\n               int a1 = find(parent, restrictions[j][0]);\n               int a2 = find(parent, restrictions[j][1]);\n               if (a1 == t1 && a2 == t2){\n                   vis = false; break;\n               }\n               else if (a1 == t2 && a2 == t1){\n                   vis = false; break;\n               }\n                else if (a1 == t1 && a2 == t1){\n                    vis = false; break;\n                }\n                else if (a1 == t2 && a2 == t2){vis = false; break;}\n               \n           }\n            if (vis == true){ans[i] = true; union(parent, requests[i][0], requests[i][1]);}\n            \n        }\n        \n        return ans; \n        \n    }\n    public int find(int[] parents, int i){\n        if (parents[i] == i) return i; \n        return find(parents, parents[i]);\n    }\n    \n    public void union(int[] parent, int a1, int a2){\n        if (find(parent, a1) == find(parent, a2)) return; \n        int s1 = find(parent, a1); int s2 = find(parent, a2);\n        parent[s2] = s1; \n        \n    }\n    \n    \n    \n}\n```
['Graph']