Accounts Merge

Join accounts that share an email into one account per person, with the emails sorted.

Each account in the list accounts is a list of strings: the first one is a name, and the rest are emails. Two accounts belong to the same person if they share at least one email, and all accounts of one person carry the same name. Two accounts with the same name may still belong to different people. Merge the accounts of each person and return one account per person: the name, then all of that person's emails in sorted order, each listed once. The accounts can come back 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 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.
Solution

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.

Emails of Example 1 as boxes. Account 1 joins john_newyork@mail.com and johnsmith@mail.com, account 2 joins johnsmith@mail.com and john00@mail.com, so the three emails form one person, John. mary@mail.com (account 3) and johnnybravo@mail.com (account 4, another John) stand alone.

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 goes from each email to its parent email. A new email starts as its own parent, a group of one. For each account, every email is joined with the account's first email, so the whole account becomes one group.

Finding a root follows parent until an email points at itself. Once the root is found, each email visited along the way gets the root as its new parent, so the next search from it takes one step. This shortcut is called path compression, and it keeps the chains short as more groups are joined.

Naming each group

Which name goes with a group? A second map, owner, goes from each email to the name on its account. All accounts of one person carry the same name, so the root's entry in owner names the whole group.

Building the sorted accounts

How does a group become an answer? After all accounts are read, each email goes into a TreeSet kept for its root. A TreeSet is Java's set that keeps its items sorted and drops repeats. For the John group that gives john00, john_newyork, johnsmith, because the character '0' comes before '_', which comes before 's'.

Java Solution

The method accountsMerge works in these steps:

  1. First, empty parent, the map from each email to its parent, with parent.clear(), and create owner, the map from each email to its account name.
  2. Go through the accounts with a loop, and keep each account's first email in first. Inside, a second loop goes over the account's emails. Each email becomes its own parent if it is new, gets its name in owner, and is joined with first by union.
  3. union(a, b) finds both roots with find and makes the root of a point at the root of b. find(x) follows parents up to the root, then points every email it passed straight at that root.
  4. Next, create groups, a map from root email to a TreeSet of emails, and put every email into the set of its root.
  5. Finally, build result: for each group, a list with the root's name from owner, then the sorted emails.

Both parent and groups are LinkedHashMaps, which remember the order in which keys were added, so the accounts come out in the order their first email appeared. The main method runs Example 1, the [a, b], [c, d], [d, b] chain, two Johns with different emails, and one account that lists the same email twice.

Java
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:

Output
[[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 putIfAbsent and the TreeSet both ignore the repeat.

The parent.clear() line matters because main reuses one object. With that line removed, the second call prints [[null, john00@mail.com, john_newyork@mail.com, johnsmith@mail.com], [null, mary@mail.com], ... before Ann's account. The emails from the first call are still in parent, but the new owner map has no name for them.

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 TreeSet of O(log E) and a few root searches that path compression keeps to O(log E) each on average.
  • Space: O(E), because parent, owner and groups each hold every email once, and the recursion in find is never deeper than the number of emails.

Union-find on numbered points, without emails, is shown in Number of Connected Components.