SDE & MLE Prep

721. Accounts Merge

Problem

Each account is [name, email1, email2, …]. Two accounts belong to the same person if they share any email (people with the same name may be different people). Merge the accounts and return each as [name, ...emails sorted]; the accounts themselves can be in any order.

Example: [["John","js@m","jny@m"],["John","js@m","j00@m"],["Mary","mary@m"]] → [["John","j00@m","jny@m","js@m"],["Mary","mary@m"]]

Union all emails within an account (to the account's first email). Then group emails by root, sort, and prefix the owner name.

Complexity: O(N log N) for N total emails (sorting).

class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
        parent, owner = {}, {}

        def find(x):
            parent.setdefault(x, x)
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        for name, *emails in accounts:
            for e in emails:
                owner[e] = name
                parent[find(e)] = find(emails[0])
        groups = defaultdict(list)
        for e in owner:
            groups[find(e)].append(e)
        return [[owner[root]] + sorted(es) for root, es in groups.items()]