Skip to content

Accounts Merge

Merge accounts that share an email with union-find, then list each person's emails in sorted order.

MediumUnion-Find
Solve on LeetCode

The problem

You get a list accounts, where each account is a name followed by some email addresses. Two accounts belong to the same person when they share at least one email, and this carries over through chains of accounts; two accounts with the same name can still be different people. Return one entry per person, made of the name followed by all of that person's emails in sorted order, with the entries themselves in any order.

Input accounts = [["Asha", "asha@mail.com", "asha.k@work.com"], ["Ravi", "ravi@mail.com"], ["Asha", "asha.k@work.com", "ak@home.com"]]

Output [["Asha", "ak@home.com", "asha.k@work.com", "asha@mail.com"], ["Ravi", "ravi@mail.com"]]

The first and third accounts share asha.k@work.com, so they become one Asha with three emails. Ravi stays on his own.

Input accounts = [["Kiran", "k1@mail.com"], ["Kiran", "k2@mail.com"]]

Output [["Kiran", "k1@mail.com"], ["Kiran", "k2@mail.com"]]

Same name, but no shared email, so these may be two different people and stay separate.

Key constraint: There can be 1,000 accounts with up to 9 emails each. Comparing every pair of accounts means about half a million list comparisons, while a map from email to account handles each email once.

How to spot the pattern

  • Records must be grouped when they share a key, and the sharing can chain through other records.
  • You don't need paths, only which records end up in the same group.

The idea

Treat each account as a node and join two accounts whenever they list the same email. A hash map from each email to the first account that listed it finds every shared email in one pass, and union-find merges the accounts as you go. At the end, every email belongs to the group of its first account, so collect the emails under each group's root, sort them and put the name in front.

Brute force: Compare the email lists of every pair of accounts to find overlaps and merge the overlapping ones, which costs O(A^2 * k) time for A accounts with k emails each.

Step by step

  1. 1Give every account its own group in a union-find over the account indices.
  2. 2Go through each account's emails, keeping a map from each email to the first account that listed it.
  3. 3If an email is already in the map, union the current account with that earlier account; otherwise add the email to the map.
  4. 4Collect each email under the root of the account that the map gives for it.
  5. 5For each root, sort its emails and put that account's name in front.

See the pattern move

The union-find pattern on a small example. Step through it, or press play.

Code

from collections import defaultdict


class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
        n = len(accounts)
        parent = list(range(n))  # every account starts as its own group
        group_size = [1] * n

        def find(x: int) -> int:
            while parent[x] != x:
                parent[x] = parent[parent[x]]  # path halving: point to the grandparent
                x = parent[x]
            return x

        def union(x: int, y: int) -> None:
            a, b = find(x), find(y)
            if a == b:
                return
            if group_size[a] < group_size[b]:
                a, b = b, a
            parent[b] = a  # hang the smaller group under the larger one
            group_size[a] += group_size[b]

        owner = {}  # email -> first account that listed it
        for i, account in enumerate(accounts):
            for email in account[1:]:
                if email in owner:
                    union(i, owner[email])  # a shared email means the same person
                else:
                    owner[email] = i

        emails_of = defaultdict(list)  # group root -> all emails of that person
        for email, i in owner.items():
            emails_of[find(i)].append(email)
        return [[accounts[root][0]] + sorted(emails) for root, emails in emails_of.items()]

Complexity

Time

O(N log N)

Space

O(N)

N is the total number of emails: each one costs a map lookup and a nearly O(1) union, and sorting every person's emails costs O(N log N) in total.

Watch out for

  • Merging accounts just because they have the same name: only a shared email proves it is the same person.
  • Merging only accounts that share an email directly and missing chains, where A shares with B and B shares with C.
  • Forgetting to drop repeated emails or to sort each person's emails.

Follow-up questions

Can you solve it with DFS instead?

Build a graph that links each email to the other emails of its account, then run a DFS from every unvisited email; each DFS collects one person's emails. With the sorting it is also O(N log N).

What if new accounts keep arriving?

Union-find handles that well: a new account only needs a union with the owners of its emails that are already in the map, so you never rebuild the groups from scratch.

In Hinglish

Har email ka pehla owner account map mein rakho. Wahi email kisi aur account mein mile toh dono accounts ka union karo; aakhir mein har root ke emails sort karke naam ke saath do.

Related problems