Union-find / Disjoint sets Solution || Faster than 90% || Java
Code\n\nclass DisjointSet {\n    private final int[] root;\n    private final int[] rank;\n    private final List<Set<Integer>> restrictions;\n\n    DisjointSet
# Code\n```\nclass DisjointSet {\n    private final int[] root;\n    private final int[] rank;\n    private final List<Set<Integer>> restrictions;\n\n    DisjointSet(int size, int[][] restrictions) {\n        root = new int[size];\n        rank = new int[size];\n        this.restrictions = new ArrayList<>();\n        for (int i = 0; i < size; i++) {\n            root[i] = i;\n            rank[i] = 1;\n            this.restrictions.add(new HashSet<>());\n        }\n        for (int[] restriction: restrictions) {\n            this.restrictions.get(restriction[0]).add(restriction[1]);\n            this.restrictions.get(restriction[1]).add(restriction[0]);\n        }\n    }\n\n    private int find(int vertex) {\n        if(root[vertex] == vertex) return vertex;\n        return root[vertex] = find(root[vertex]);\n    }\n\n    public boolean union(int vertex1, int vertex2) {\n        int root1 = find(vertex1);\n        int root2 = find(vertex2);\n        if(root1 == root2) return true;\n        if(notRestricted(root1, root2)) {\n            if(rank[root1] > rank[root2]) {\n                root[root2] = root1;\n                restrictions.get(root1).addAll(restrictions.get(root2));\n                addRoots(root1);\n            } else if(rank[root2] > rank[root1]) {\n                root[root1] = root2;\n                restrictions.get(root2).addAll(restrictions.get(root1));\n                addRoots(root2);\n            } else {\n                root[root2] = root1;\n                rank[root1]++;\n                restrictions.get(root1).addAll(restrictions.get(root2));\n                addRoots(root1);\n            }\n            return true;\n        }\n        return false;\n    }\n\n    private void addRoots(int index) {\n        Set<Integer> added = new HashSet<>();\n        for (int node: restrictions.get(index)) \n            added.add(find(node));\n        restrictions.get(index).addAll(added);    \n    }\n\n    private boolean notRestricted(int root1, int root2) {\n        for (int node: restrictions.get(root1)) if(node == root2) return false;\n        for (int node: restrictions.get(root2)) if(node == root1) return false;\n        return true;\n    }\n}\n\nclass Solution {\n    public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) {\n        DisjointSet set = new DisjointSet(n, restrictions);\n        boolean[] queries = new boolean[requests.length];\n        for (int i = 0; i < requests.length; i++) \n            queries[i] = set.union(requests[i][0], requests[i][1]);\n        return queries;\n    }\n}\n```
['Java']