[C++] Union find/ DisjointSet || Self Explanatory Code
\n# Code\ncpp []\nclass DisjointSet {\n    vector<int> parent, rank;\npublic:\n    DisjointSet(int n) {\n        rank.resize(n, 0);\n        parent.resize(n);\n
\n# Code\n```cpp []\nclass DisjointSet {\n    vector<int> parent, rank;\npublic:\n    DisjointSet(int n) {\n        rank.resize(n, 0);\n        parent.resize(n);\n        iota(parent.begin(), parent.end(), 0);\n    }\n\n    int find(int node) {\n        if(node == parent[node]) return node;\n        return parent[node] = find(parent[node]);\n    }\n\n    void unionByRank(int u, int v) {\n        int rootU = find(u);\n        int rootV = find(v);\n\n        if(rootU == rootV) return;\n\n        if(rank[rootU] < rank[rootV]) {\n            parent[rootU] = rootV;\n        } else if(rank[rootU] > rank[rootV]) {\n            parent[rootV] = rootU;\n        } else {\n            parent[rootV] = rootU;\n            rank[rootU]++;\n        }\n    }\n\n    bool isInSameComponent(int u, int v) {\n        return find(u) == find(v);\n    }\n};\n\nclass Solution {\npublic:\n    vector<bool> friendRequests(int n, vector<vector<int>>& restrictions, vector<vector<int>>& requests) {\n        DisjointSet ds(n);\n        vector<bool> result(requests.size());\n\n        for(int i = 0; i < requests.size(); ++i) {\n            int u = requests[i][0], v = requests[i][1];\n            int rootU = ds.find(u);\n            int rootV = ds.find(v);\n\n            bool canBecomeFriends = true;\n            if(rootU != rootV) {\n                for(auto& restriction : restrictions) {\n                    int x = restriction[0], y = restriction[1];\n                    int rootX = ds.find(x), rootY = ds.find(y);\n\n                    if((rootU == rootX && rootV == rootY) ||(rootU == rootY && rootV == rootX)) {\n                        canBecomeFriends = false;\n                        break;\n                    }\n                }\n            }\n\n            if(canBecomeFriends) {\n                ds.unionByRank(u, v);\n                result[i] = true;\n            } else {\n                result[i] = false;\n            }\n        }\n\n        return result;\n    }\n};\n\n```
['C++']