Accounts Merge
Join accounts that share an email into one account per person, with the emails sorted.
Each account in the list accounts
Example 1
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Explanation: the first two accounts share johnsmith@mail.com, so they belong to one John. The last account shares no email with them, so it belongs to a different John.
The Idea
Imagine a shop whose customers signed up several times, once on the website and once in the app, sometimes with a new email added. The shop wants one record per real customer. Names are no help, because two different customers can both be called John. An email, though, belongs to one person only, so two sign-ups that share an email are the same customer.
Example 1 has four accounts. Look at the picture below: each box is one email, and a line joins two emails that appear in the same account.
The line labelled account 1 joins john_newyork@mail.com and johnsmith@mail.com. The line labelled account 2 joins johnsmith@mail.com and john00@mail.com. The box in the middle, johnsmith@mail.com, is in both accounts, so all three emails end up in the group labelled "one person: John". Account 3, Mary, and account 4, another John, touch nothing else and stay as groups of one email each.
So the answer is a set of groups of emails, and the question is how to build the groups. A link can also be indirect. Take the accounts [a, b], [c, d] and [d, b], with a to d standing for four emails. The first two accounts share nothing, yet the third shares d with one and b with the other, so all three belong to one person.
The key insight is to give every group one email that speaks for it. Each email keeps a note of another email in its group, its parent. Following parent after parent ends at an email whose parent is itself, the group's root. Two emails are in the same group exactly when they reach the same root. To join two groups, the root of one gets the other root as its parent. Keeping groups this way, with a "find the root" step and a "join two groups" step, is called union-find.
Solution Approach
Turning that idea into code means settling four things: why not merge accounts by comparing them directly, how the parent notes are stored and joined, where each group's name comes from, and how each group is turned into a sorted account.
Comparing accounts directly
Why not compare every pair of accounts and merge the two whenever they share an email? One round is not enough, because merging can create new shared emails, as with [a, b], [c, d] and [d, b]. The rounds have to repeat until nothing changes, and each round compares every pair, which grows quickly with many accounts. Union-find reads each email once and joins groups as it goes, so no repeated rounds are needed.
Storing and joining the parent notes
How are the parent notes kept? A map named parent
Finding a root follows parent
Naming each group
Which name goes with a group? A second map, ownerowner
Building the sorted accounts
How does a group become an answer? After all accounts are read, each email goes into a TreeSetTreeSet'0''_''s'
Java Solution
The method accountsMerge
- First, empty
, the map from each email to its parent, withparent , and createparent.clear() , the map from each email to its account name.owner - Go through the accounts with a loop, and keep each account's first email in
. Inside, a second loop goes over the account's emails. Each email becomes its own parent if it is new, gets its name infirst , and is joined withowner byfirst .union finds both roots withunion(a, b) and makes the root offind point at the root ofa .b follows parents up to the root, then points every email it passed straight at that root.find(x)- Next, create
, a map from root email to agroups of emails, and put every email into the set of its root.TreeSet - Finally, build
: for each group, a list with the root's name fromresult , then the sorted emails.owner
Both parentgroupsLinkedHashMapmain
import java.util.*;
public class AccountsMerge {
private final Map<String, String> parent = new LinkedHashMap<>(); // email -> parent email
public List<List<String>> accountsMerge(List<List<String>> accounts) {
parent.clear(); // start fresh on every call
Map<String, String> owner = new HashMap<>(); // email -> account name
for (List<String> acc : accounts) {
String first = acc.get(1);
for (int i = 1; i < acc.size(); i++) {
String email = acc.get(i);
parent.putIfAbsent(email, email);
owner.put(email, acc.get(0));
union(first, email); // every email in one account belongs together
}
}
Map<String, TreeSet<String>> groups = new LinkedHashMap<>(); // root -> sorted emails
for (String email : parent.keySet()) {
groups.computeIfAbsent(find(email), k -> new TreeSet<>()).add(email);
}
List<List<String>> result = new ArrayList<>();
for (Map.Entry<String, TreeSet<String>> g : groups.entrySet()) {
List<String> merged = new ArrayList<>();
merged.add(owner.get(g.getKey()));
merged.addAll(g.getValue());
result.add(merged);
}
return result;
}
private String find(String x) {
String p = parent.get(x);
if (!p.equals(x)) {
p = find(p);
parent.put(x, p); // path compression
}
return p;
}
private void union(String a, String b) {
parent.put(find(a), find(b));
}
public static void main(String[] args) {
AccountsMerge m = new AccountsMerge();
System.out.println(m.accountsMerge(List.of(
List.of("John", "johnsmith@mail.com", "john_newyork@mail.com"),
List.of("John", "johnsmith@mail.com", "john00@mail.com"),
List.of("Mary", "mary@mail.com"),
List.of("John", "johnnybravo@mail.com"))));
System.out.println(m.accountsMerge(List.of(
List.of("Ann", "a@mail.com", "b@mail.com"),
List.of("Ann", "c@mail.com", "d@mail.com"),
List.of("Ann", "d@mail.com", "b@mail.com"))));
System.out.println(m.accountsMerge(List.of(
List.of("John", "a@mail.com"),
List.of("John", "b@mail.com"))));
System.out.println(m.accountsMerge(List.of(
List.of("Lee", "z@mail.com", "y@mail.com", "z@mail.com"))));
}
}
Running it prints:
[[John, john00@mail.com, john_newyork@mail.com, johnsmith@mail.com], [Mary, mary@mail.com], [John, johnnybravo@mail.com]]
[[Ann, a@mail.com, b@mail.com, c@mail.com, d@mail.com]]
[[John, a@mail.com], [John, b@mail.com]]
[[Lee, y@mail.com, z@mail.com]]
The first line matches Example 1: one John with three sorted emails, Mary, and the John with johnnybravo@mail.com on his own. The second line shows the indirect link at work. Ann's three accounts became one account with a, b, c and d, although the first two accounts share no email.
The third line keeps two accounts named John, because a@mail.com and b@mail.com never meet; merging by name would have joined them into one. In the last line, z@mail.com was listed twice in Lee's account but appears once, since putIfAbsentTreeSet
The parent.clear()main[[null, john00@mail.com, john_newyork@mail.com, johnsmith@mail.com], [null, mary@mail.com], ...parentowner
Complexity
The work is one union per email, one find per email to group them, and one sorted insert per email.
- Time: O(E log E), where E is the total number of emails in all accounts, because each email costs one insert into a
of O(log E) and a few root searches that path compression keeps to O(log E) each on average.TreeSet - Space: O(E), because
,parent andowner each hold every email once, and the recursion ingroups is never deeper than the number of emails.find
Union-find on numbered points, without emails, is shown in