You are given a list of accounts. Each account is a name followed by one or more email addresses. Two accounts belong to the same person if they share at least one email. Different people can have the same name.
Return the merged accounts: for each person, their name followed by all of their emails in sorted order. The accounts can be in any order.
Example 1
Input: [["ana","ana@x.com","ana.w@x.com"],
["ana","ana@x.com","a@y.com"],
["bo","bo@y.com"]]
Output: [["ana","a@y.com","ana.w@x.com","ana@x.com"],
["bo","bo@y.com"]]1 more example and the constraints
Example 2
Input: [["cy","cy@q.com"]] Output: [["cy","cy@q.com"]]
Constraints
- 1 ≤ number of accounts ≤ 1,000
- Each account has 2 to 10 entries
- Emails are lower-case, at most 30 characters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Brute forceO(A²·k) per pass
- Graph + DFSO(n log n)
- Union-FindO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 accounts | Verdict |
|---|---|---|---|
| Brute force | O(A²·k) × passes | Mention it, then move on | |
| Graph + DFS | O(n log n) | Passes; easy to explain | |
| Union-Find | O(n log n) | Best; merges as you read |
A = accounts, k = emails per account, n = total emails.
Edge cases to test
- One email only. [["cy","cy@q.com"]] must still be returned.
- Same name, different people. Two “ana” accounts with no shared email stay separate.
- Duplicate email in one account. Should appear once in the output.
- One email links many accounts. All of them collapse into one person.
Common mistakes
- Skipping accounts with a single email, so they vanish from the output.
- Merging by name. Names are not unique.
- Forgetting to sort, or sorting the name in with the emails.
How to talk through it
- 1Clarify. Can two people share a name? Can an account list the same email twice?
- 2Give the brute force. Compare every pair and merge; state why it is slow.
- 3Reframe as a graph. Emails are nodes, shared accounts are edges, people are components.
- 4Code Union-Find. Say what find and union do as you write them.
- 5Test out loud. Run the single-email and same-name cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?