1
// if you like this, please give me a upvote4
int parents[1001]; // why 1001? becoz it is max length of accounts, see5
// constraints (1 <= accounts.length <= 1000)7
// function to find original parent8
int findpar(int parents[], int to_find) {9
while (parents[to_find] != to_find) to_find = parents[to_find];14
vector<vector<string>> accountsMerge(vector<vector<string>> &accounts) {15
// Link each email to their respective orginal parent,16
// we will do it by linking each email to its unique id17
unordered_map<string, int> email_to_id;19
for (int i = 0; i < accounts.size(); i++) // traversing from each row21
parents[i] = i; // intially we don't know anything, so every parent is22
// unique id of itself24
// why we start from 1? becoz emails starting from this place25
for (int j = 1; j < accounts[i].size(); j++) {26
// we check if this particular email already got their unique id, if yes27
// then we link it to its original parent unique id28
if (email_to_id.find(accounts[i][j]) != email_to_id.end()) {29
int parent1 = findpar(parents, i);30
int parent2 = findpar(parents, email_to_id[accounts[i][j]]);32
parents[parent1] = parent2;33
} else // if not find, then just give it to exsiting parent35
email_to_id[accounts[i][j]] = parents[i];40
// Now, we create a map that store all email id with their unique ids41
// id, vector of all emails42
unordered_map<int, vector<string>> resultant_map;44
for (auto it : email_to_id) {45
int uniq_id = findpar(parents, it.second);46
resultant_map[uniq_id].push_back(it.first);49
// uff tired, so now towards final ans50
vector<vector<string>> ans;51
for (auto it : resultant_map) {52
vector<string> email = it.second;54
// question demand in sorted order55
sort(email.begin(), email.end());57
// inserting name in starting with the help of unique id58
email.insert(email.begin(), accounts[it.first][0]);