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.
We can solve this problem using graph traversal techniques:
Graph construction: Treat emails as nodes and create edges between them whenever they appear in the same account. Use a map to associate emails with names.
Connected components discovery: Use either DFS or Union-Find to group connected emails.
Result generation: Collect all emails in each connected component and format the output as required (name, sorted emails).
classSolution:
defaccountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
# Step 1: Build adjacency graph email_to_name: Dict[str, str] = {}
graph: Dict[str, List[str]] = {}
for acc in accounts:
name = acc[0]
for email in acc[1:]:
email_to_name[email] = name
# Build edges between all emails in the same accountif email notin graph:
graph[email] = []
graph[email].append(acc[1]) # Link to the initial email graph[acc[1]].append(email) # Link initial email to this one# Step 2: Traverse connected components visited = set()
ans = []
defdfs(email: str, group: List[str]):
visited.add(email)
group.append(email)
for neigh in graph[email]:
if neigh notin visited:
dfs(neigh, group)
for email in graph:
if email notin visited:
group = [] # Collect connected emails dfs(email, group)
group.sort() # Sort emails alphabetically ans.append([email_to_name[email]] + group)
return ans