Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
Example 1:
Input: accounts = [[“John”,“johnsmith@mail.com”,“john_newyork@mail.com”],[“John”,“johnsmith@mail.com”,“john00@mail.com”],[“Mary”,“mary@mail.com”],[“John”,“johnnybravo@mail.com”]] Output: [[“John”,“john00@mail.com”,“john_newyork@mail.com”,“johnsmith@mail.com”],[“Mary”,“mary@mail.com”],[“John”,“johnnybravo@mail.com”]] Explanation: The first and second John’s are the same person as they have the common email “johnsmith@mail.com”. The third John and Mary are different people as none of their email addresses are used by other accounts. We could return these lists in any order, for example the answer [[‘Mary’, ‘mary@mail.com’], [‘John’, ‘johnnybravo@mail.com’], [‘John’, ‘john00@mail.com’, ‘john_newyork@mail.com’, ‘johnsmith@mail.com’]] would still be accepted.
Example 2:
Input: accounts = [[“Gabe”,“Gabe0@m.co”,“Gabe3@m.co”,“Gabe1@m.co”],[“Kevin”,“Kevin3@m.co”,“Kevin5@m.co”,“Kevin0@m.co”],[“Ethan”,“Ethan5@m.co”,“Ethan4@m.co”,“Ethan0@m.co”],[“Hanzo”,“Hanzo3@m.co”,“Hanzo1@m.co”,“Hanzo0@m.co”],[“Fern”,“Fern5@m.co”,“Fern1@m.co”,“Fern0@m.co”]] Output: [[“Ethan”,“Ethan0@m.co”,“Ethan4@m.co”,“Ethan5@m.co”],[“Gabe”,“Gabe0@m.co”,“Gabe1@m.co”,“Gabe3@m.co”],[“Hanzo”,“Hanzo0@m.co”,“Hanzo1@m.co”,“Hanzo3@m.co”],[“Kevin”,“Kevin0@m.co”,“Kevin3@m.co”,“Kevin5@m.co”],[“Fern”,“Fern0@m.co”,“Fern1@m.co”,“Fern5@m.co”]]
Constraints:
1 <= accounts.length <= 10002 <= accounts[i].length <= 101 <= accounts[i][j].length <= 30accounts[i][0]consists of English letters.accounts[i][j] (for j > 0)is a valid email.
Approach: Union-Find Over Emails
Algorithm
- Assign an index to every account and map each email to the index of the account that first contains it
- When a new email already maps to a previous account index, union the two account indices (they belong to the same person)
- Group all emails by the root index of their account
- For each group, build the output list as
[name, sorted emails...]
Time & Space Complexity
- Time Complexity: O(A * E * log(A * E)) - dominated by sorting emails, with near-O(1) union-find operations
- Space Complexity: O(A * E) - the email-to-account map and the grouped results
Java Implementation
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class AccountsMerge {
private int[] parent;
private int[] rank;
/**
* Merge accounts that share at least one common email.
* @param accounts List of [name, email...]
* @return Merged accounts with sorted emails
*/
public List<List<String>> accountsMerge(List<List<String>> accounts) {
int n = accounts.size();
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
Map<String, Integer> emailToId = new HashMap<>();
for (int i = 0; i < n; i++) {
List<String> account = accounts.get(i);
for (int j = 1; j < account.size(); j++) {
String email = account.get(j);
if (emailToId.containsKey(email)) {
union(i, emailToId.get(email));
} else {
emailToId.put(email, i);
}
}
}
Map<Integer, List<String>> grouped = new TreeMap<>();
for (Map.Entry<String, Integer> entry : emailToId.entrySet()) {
int root = find(entry.getValue());
grouped.computeIfAbsent(root, k -> new ArrayList<>()).add(entry.getKey());
}
List<List<String>> result = new ArrayList<>();
for (Map.Entry<Integer, List<String>> entry : grouped.entrySet()) {
List<String> emails = entry.getValue();
Collections.sort(emails);
List<String> merged = new ArrayList<>();
merged.add(accounts.get(entry.getKey()).get(0));
merged.addAll(emails);
result.add(merged);
}
return result;
}
private int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
private void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) {
return;
}
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
// Test method
public static void main(String[] args) {
AccountsMerge am = new AccountsMerge();
List<List<String>> accounts = new ArrayList<>();
accounts.add(List.of("John", "johnsmith@mail.com", "john_newyork@mail.com"));
accounts.add(List.of("John", "johnsmith@mail.com", "john00@mail.com"));
accounts.add(List.of("Mary", "mary@mail.com"));
accounts.add(List.of("John", "johnnybravo@mail.com"));
System.out.println("Input: accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]");
System.out.println("Output: " + am.accountsMerge(accounts));
}
}
Example Walkthrough
For the four accounts in Example 1:
- Email
johnsmith@mail.comappears in accounts 0 and 1 -> union(0, 1) - The other emails belong to accounts 2 and 3 with no sharing
- Roots: account 0 (John, with johnsmith, john_newyork, john00), account 2 (Mary), account 3 (Johnny Bravo John)
- Emails sorted per root, name from the root account
Key Points
- Email as Key: Emails are unique identifiers that connect accounts, not names
- Same Name Trap: Identical names do not imply the same person; only shared emails do
- Union-Find: Merges account indices whenever a repeated email is seen
- Sorted Output: Each group’s emails must be sorted; the accounts themselves may be in any order
- Grouping: After unioning, collect emails by the root index to form the final accounts