Python coding

Merge contact cards that share an email

Each contact card is a list [name, email, email, ...] with a name and one or more emails. Two cards belong to the same person when they share an email, directly or through a chain of other cards; a shared name alone proves nothing. Return one merged card per person: the name followed by all of that person's emails, sorted and without repeats. The merged cards can be in any order.

Cards of the same person always carry the same name.

Besides the tests, one large input (450 cards) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • merge_cards([["Ana","ana@x.io","a@y.io"],["Leo","leo@x.io"],["Ana","a@y.io","ana@z.io"]]) → [["Ana","a@y.io","ana@x.io","ana@z.io"],["Leo","leo@x.io"]]
  • merge_cards([["Sam","sam@x.io"],["Sam","sam@y.io"]]) → [["Sam","sam@x.io"],["Sam","sam@y.io"]]
  • merge_cards([["Eva","e1@x.io","e2@x.io"],["Eva","e3@x.io","e4@x.io"],["Eva","e4@x.io","e1@x.io"]]) → [["Eva","e1@x.io","e2@x.io","e3@x.io","e4@x.io"]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Emails are the nodes. Every card says: all of my emails belong to one group. That is a series of unions.

Hint 2

Union each email on a card with the card's first email, using a dict as the parent map. Remember each email's name on the way.

Hint 3

After all the unions, group every email under find(email), then sort each group. Merging card by card instead misses a late card that bridges two earlier groups.

Solution and why it works
pythonO(E log E), E = total emails · O(E)
def merge_cards(cards: list[list[str]]) -> list[list[str]]:
    parent, owner = {}, {}                   # email -> parent email, email -> name

    def find(x: str) -> str:
        while parent[x] != x:
            parent[x] = parent[parent[x]]    # path halving
            x = parent[x]
        return x

    for name, *emails in cards:
        for email in emails:
            parent.setdefault(email, email)
            owner[email] = name
            parent[find(email)] = find(emails[0])    # link roots, never the emails themselves
    groups = {}
    for email in parent:
        groups.setdefault(find(email), []).append(email)
    return [[owner[root], *sorted(members)] for root, members in groups.items()]

Treat each email as a node and each card as a set of unions joining its emails. Union-find merges groups transitively and in any order, so a late card that bridges two earlier groups just links their roots. One final pass groups every email under its root, and sorting each group gives the merged card. Names can't be the key: two people may share one. Always link roots, parent[find(a)] = find(b); linking the emails themselves can detach part of a group.