Merge Accounts by Shared Email
Company: Electronic
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
## Merge Accounts by Shared Email
Each account record begins with a person's name followed by one or more email addresses. Two records belong to the same person if they share at least one email address, directly or through a chain of shared addresses. Merge all records that refer to the same person.
### Function Signature
```python
def merge_accounts(accounts: list[list[str]]) -> list[list[str]]:
...
```
### Input
- Each record has the form `[name, email_1, email_2, ...]`.
- Every email address belongs to exactly one real person.
- Records for the same real person use the same name.
### Output
Return one record per person. Each output record must contain the person's name followed by all of their distinct email addresses in lexicographic order. The order of person records does not matter.
### Constraints
- `1 <= len(accounts) <= 10_000`
- Each account contains at least one email address.
- The total number of email occurrences is at most `200_000`.
### Example
```text
Input:
[
["John", "johnsmith@mail.com", "john_newyork@mail.com"],
["John", "johnsmith@mail.com", "john00@mail.com"],
["Mary", "mary@mail.com"],
["John", "johnnybravo@mail.com"]
]
One valid output:
[
["John", "john00@mail.com", "john_newyork@mail.com", "johnsmith@mail.com"],
["Mary", "mary@mail.com"],
["John", "johnnybravo@mail.com"]
]
```
### Clarifications
- Sharing is transitive: if record A shares an email with B and B shares another email with C, all three records merge.
- Duplicate occurrences of the same email must appear only once in the merged record.
Quick Answer: Merge account records connected directly or transitively by shared email addresses. Deduplicate and sort each person's emails while handling up to 200,000 email occurrences with an efficient graph or disjoint-set approach.
Merge account records connected directly or transitively by shared email, deduplicate and sort each person's emails. For deterministic grading, order merged person records by the earliest input-record index in each component.
Constraints
- At most 10000 account records
- Each record has at least one email
- Records for one real person use one name
- Order merged person records by each component's earliest input-record index
Examples
Input: [['A', 'a@x']]
Expected Output: [['A', 'a@x']]
Explanation: A single account remains unchanged.
Input: [['John', 'a@x', 'b@x'], ['John', 'b@x', 'c@x']]
Expected Output: [['John', 'a@x', 'b@x', 'c@x']]
Explanation: A shared email merges both records.
Hints
- Treat records sharing an email as connected components.
- Union-find can merge components as each email is encountered.