Unify Contact Profiles Linked by Common Email Addresses
Trees & GraphsModel answerLast updated
Combine contact records that are directly or transitively linked by a shared email, outputting each person's name with a deduplicated, sorted email list.
Consolidate Duplicate Profiles
A system stores profiles as lists of strings. The first string in each list is the profile's display name. Every following string is an email address tied to that profile.
Two profiles describe the same person whenever they have at least one email in common. This relation is transitive: if profile A shares an email with B, and B shares one with C, then A, B and C are all the same person, even if A and C have nothing in common directly.
Write a function that consolidates the profiles. Each consolidated profile must contain:
- the display name, followed by
- every distinct email from all the profiles that were merged into it, in ascending lexicographic order.
def merge_accounts(accounts: list[list[str]]) -> list[list[str]]:
Rules
- Only a shared email links two profiles. Having the same name is never a reason to merge.
- Two profiles with equal names but no email connection (direct or through a chain) must stay separate.
- A single profile can list the same email more than once. The output must contain it only once.
- The order of the returned profiles is not specified, but listing them by the position of each group's first profile is a sensible choice.
Constraints
1 <= len(accounts) <= 10002 <= len(accounts[i]) <= 101 <= len(accounts[i][j]) <= 30
Examples
Example 1
Input: [['John', '[email protected]', '[email protected]'], ['John', '[email protected]', '[email protected]'], ['Mary', '[email protected]']]
Output: [['John', '[email protected]', '[email protected]', '[email protected]'], ['Mary', '[email protected]']]
Example 2
Input: [['Gabe', '[email protected]', '[email protected]'], ['Gabe', '[email protected]'], ['Gabe', '[email protected]', '[email protected]']]
Output (following the rules above): [['Gabe', '[email protected]', '[email protected]', '[email protected]'], ['Gabe', '[email protected]']]
The first and third profiles are joined through [email protected]. The middle profile shares no email with either, so it stays on its own even though the name matches.
What to cover in your answer
- How you model the problem and why it is correct.
- The algorithm, its time and space complexity, and working code.
- The edge cases you would check.
- How you would adapt the approach for a very large dataset, or if the output had to list a primary email first.
Hints
Hint 1
Think of the profiles (or the emails) as nodes in a graph. Which pairs should be joined by an edge, and what does a merged person correspond to in that graph?
Hint 2
Avoid comparing every pair of profiles. Instead, remember for each email which profile you saw it in first, and link any later profile that contains the same email to that one.
Hint 3
A disjoint set union over profile indices handles transitivity automatically. After all links are made, collect emails into a set per root, then output the name plus the sorted set.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model
Treat each profile as a node. Two profiles are connected if they share an email. A single person is a connected component of this graph, and transitivity comes for free: A–B and B–C put all three in one component.
Names play no role in linking. That is why Example 2 yields two groups: the middle profile has no email in common with the others.
Approach with Disjoint Set Union
- Create a DSU over profile indices
0..n-1, with path compression and union by size. - Keep a dictionary
ownermapping each email to the first profile index in which it appeared. - For each profile
iand each of its emails:- If the email is already in
owner, unioniwithowner[email]. - Otherwise record
owner[email] = i.
- If the email is already in
- After all unions, iterate over profiles again. Use
find(i)to get the component root and add that profile's emails to a set stored under the root. Remember the name from the first profile that reached the root. - For each component, output
[name] + sorted(emails).
This avoids pairwise comparison of profiles, which would cost O(N²·K). Each email is handled a constant number of times.
Why it is correct
- Soundness: a union happens only when two profiles literally contain the same email, so every merge is justified.
- Completeness: take a chain of profiles where each adjacent pair shares an email. When the later profile of a pair is processed, the shared email is already in
owner, pointing to the earlier profile or to something already unioned with it. Each link therefore causes a union, and by induction the entire chain lands in one set. - Same name, no shared email: never unioned, so they remain separate.
- Duplicate emails inside a profile: the second occurrence maps to the same index, so
union(i, i)does nothing, and the set removes the repeat from the output.
Complexity
Let N be the number of profiles and E the total number of email strings (at most 9 per profile, so E ≤ 9000 here).
- Time: O(E · α(N)) for the DSU work plus O(E log E) for sorting, so O(E log E) overall.
- Space: O(E + N) for the owner map, the per-component sets and the DSU arrays.
Code
def merge_accounts(accounts: list[list[str]]) -> list[list[str]]:
n = len(accounts)
parent = list(range(n))
size = [1] * n
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
def union(a: int, b: int) -> None:
ra, rb = find(a), find(b)
if ra == rb:
return
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
owner: dict[str, int] = {}
for i, acc in enumerate(accounts):
for email in acc[1:]:
if email in owner:
union(i, owner[email])
else:
owner[email] = i
groups: dict[int, tuple[str, set[str]]] = {}
for i, acc in enumerate(accounts):
root = find(i)
if root not in groups:
groups[root] = (acc[0], set())
groups[root][1].update(acc[1:])
return [[name] + sorted(emails) for name, emails in groups.values()]
Python dictionaries keep insertion order, so groups come out ordered by the first profile that reached each root. Under these rules, Example 1 gives the stated output and Example 2 gives the two Gabe groups.
Alternative: graph traversal
Build an adjacency list over emails by linking the first email of each profile to the rest, remembering which name each email belongs to. Then run an iterative DFS or BFS from every unvisited email, collecting the component, and sort it. The complexity is the same. Use an iterative traversal, because a recursive DFS on a long chain can exceed Python's recursion limit.
Edge cases
- A single profile: return it with duplicates removed and emails sorted.
- Same name, disjoint emails: separate outputs.
- A profile with the same email repeated: deduplicated.
- Long transitive chains: fine with DSU.
- Output order is unspecified, so clarify it up front or sort the result if the checker needs determinism.
Common mistakes
- Merging by name, which breaks the rule and gives the wrong answer on Example 2.
- Merging only once, instead of handling chains, when using a naive "merge pairs repeatedly" approach.
- Forgetting to deduplicate or sort emails.
- Using recursive DFS without considering depth.
- Not noticing that a naive reading of Example 2 suggests one merged group, and failing to clarify the rule with the interviewer.
Follow-ups
Very large data. Do not hold raw strings in memory. Hash or dictionary-encode emails into 64-bit integer IDs and run DSU on compact integer arrays, possibly memory-mapped. Beyond one machine, compute connected components in a distributed way: shard by email hash to emit (profile, profile) edges, then resolve components with union-find rounds or min-label propagation on a framework such as Spark. Emit (email_id, component_id) pairs and build sorted lists lazily per component.
Primary email first. Carry a primary field per profile. If merged profiles have conflicting primaries, choose by a defined policy such as earliest profile or most recently verified. Output [name, primary] + sorted(emails - {primary}). The DSU does not change, only the aggregation step.
Conflicting names for one component. The graph still merges, since emails are the identity key. Decide which name to emit: majority vote, most recent record, a trusted source, or keep all as aliases. In production, flag such components for review. Shared addresses like a company-wide inbox can falsely join unrelated people, so consider refusing to use an email as a merge key once it links too many distinct identities.