Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
Example 1:
Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]] Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]] Explanation: The first and second John's are the same person as they have the common email "johnsmith@mail.com". The third John and Mary are different people as none of their email addresses are used by other accounts. We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
Example 2:
Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]] Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]
Constraints:
1 <= accounts.length <= 10002 <= accounts[i].length <= 101 <= accounts[i][j].length <= 30accounts[i][0] consists of English letters.accounts[i][j] (for j > 0) is a valid email.The key challenge in Accounts Merge is identifying accounts that belong to the same person when they share common email addresses. Although names may repeat, the true connection is the email. A common strategy is to model the problem as a graph where emails are nodes and shared accounts create edges between them.
One efficient method uses Union-Find (Disjoint Set Union). Each email is treated as a node, and emails within the same account are unioned together. After processing all accounts, emails belonging to the same root form a merged group. Finally, the grouped emails are sorted and paired with the account name.
Another approach builds an adjacency list and uses Depth-First Search (DFS) or Breadth-First Search (BFS) to traverse connected components of emails.
Union-Find typically provides near-linear performance with path compression. Both approaches require sorting the resulting email lists for the final output.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Union-Find (Disjoint Set) | O(N log N) | O(N) |
| Graph + DFS/BFS | O(N log N) | O(N) |
take U forward
Use these hints if you're stuck. Try solving on your own first.
For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph.
In this approach, we treat each email as a node in a graph and create edges between nodes that appear in the same account. By doing so, connected components in the graph will represent emails belonging to the same person.
Once the graph is constructed, we perform a Depth-First Search (DFS) to enumerate all emails in each connected component, sort the collected emails, and then append the owner’s name to produce the final result.
Time complexity is O(NK log NK), where N is the number of accounts, and K is the maximum number of emails in an account, due to sorting each component. Space complexity is O(NK) for storing the graph and visited nodes.
1#include <iostream>
2#include <vector>
3#include <unordered_map>
4#include <unordered_set>
5#include <set>
6#include <string>
7using namespace std;
8
9void dfs(const string &email, unordered_map<string, unordered_set<string>> &emailGraph,
10 unordered_set<string> &visited, vector<string> &component) {
11 visited.insert(email);
12 component.push_back(email);
13 for (const string &neighbor : emailGraph[email]) {
14 if (!visited.count(neighbor)) {
15 dfs(neighbor, emailGraph, visited, component);
16 }
17 }
18}
19
20vector<vector<string>> accountsMerge(vector<vector<string>> &accounts) {
21 unordered_map<string, unordered_set<string>> emailGraph;
22 unordered_map<string, string> emailToName;
23
24 // Build the graph
25 for (const auto &account : accounts) {
26 const string &name = account[0];
27 for (int j = 1; j < account.size(); ++j) {
28 emailGraph[account[1]].insert(account[j]);
29 emailGraph[account[j]].insert(account[1]);
30 emailToName[account[j]] = name;
31 }
32 }
33
34 // DFS to find connected components
35 unordered_set<string> visited;
36 vector<vector<string>> result;
37 for (const auto &pair : emailGraph) {
38 const string &email = pair.first;
39 if (!visited.count(email)) {
40 vector<string> component;
41 dfs(email, emailGraph, visited, component);
42 sort(component.begin(), component.end());
43 component.insert(component.begin(), emailToName[email]);
44 result.push_back(component);
45 }
46 }
47 return result;
48}In this C++ solution, a graph is constructed using an unordered_map to label each email and its connections. The process involves traversing the graph with a DFS to find interconnected emails, then sorting them.
This approach uses a Union-Find data structure for efficient merging of accounts. Each email is identified with a parent, initially itself, and accounts are unified if they share an email. We then deduce separate email sets from parent-child relationships.
Time complexity is O(NK log NK) due to sorting each email list. Space complexity is O(NK) owing to email mappings and Union-Find arrangements.
1var accountsMerge = function(accounts) {
2
Watch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Yes, Accounts Merge is a common interview-style problem because it tests graph modeling, union-find, and data structure design. It frequently appears in coding interviews at large tech companies.
Union-Find is typically the best data structure because it efficiently tracks connected components. Alternatively, you can build a graph of emails and use DFS or BFS to find connected groups that represent merged accounts.
The most efficient approach is Union-Find (Disjoint Set Union). It groups emails belonging to the same account by connecting them under a common parent. With path compression and union by rank, the operations become nearly constant time, making it very scalable.
Emails uniquely identify connections between accounts, while names may repeat across different people. If two accounts share the same email, they must belong to the same person, which allows us to merge them.
The JavaScript solution leverages an object for Union-Find representation. After creating initial email relations, emails are unified under a common parent, gathered to generate connected components, which are finally sorted for the output.