#721

Accounts Merge

Medium
ArrayHash TableStringDepth-First SearchBreadth-First SearchUnion-FindSortingGraph Traversal (DFS, BFS)Union-Find
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + e), where n is the number of accounts and e is the number of emails.
Space
O(1)
O(n + e)
💡

Intuition

Time O(n + e), where n is the number of accounts and e is the number of emails.Space O(n + e)

We can model this problem as a graph where emails are nodes and edges exist between emails that belong to the same account. Using DFS or Union-Find, we can efficiently find connected components.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a graph where each email is a node and edges connect emails from the same account.
  2. 2Step 2: Use DFS or Union-Find to find connected components of emails.
  3. 3Step 3: For each connected component, collect emails, sort them, and prepend the account name.
solution.py29 lines
1from collections import defaultdict
2
3def accountsMerge(accounts):
4    graph = defaultdict(set)
5    for account in accounts:
6        name = account[0]
7        for i in range(2, len(account)):
8            graph[account[i]].add(account[i-1])
9            graph[account[i-1]].add(account[i])
10    visited = set()
11    merged_accounts = []
12
13    def dfs(email):
14        stack = [email]
15        component = []
16        while stack:
17            node = stack.pop()
18            if node not in visited:
19                visited.add(node)
20                component.append(node)
21                stack.extend(graph[node])
22        return component
23
24    for account in accounts:
25        for email in account[1:]:
26            if email not in visited:
27                component = dfs(email)
28                merged_accounts.append([account[0]] + sorted(component))
29    return merged_accounts

Complexity note: This complexity is due to the graph traversal, where we visit each email and its connections.

  • 1Understanding the relationship between emails is crucial; they form a graph where merging accounts is about finding connected components.
  • 2Using graph traversal techniques like DFS or Union-Find can significantly optimize the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.