Leetcode 721: Accounts Merge

grid47
grid47
Exploring patterns and algorithms
Aug 26, 2024 6 min read

A set of accounts where identical accounts are merged, with each merge softly glowing as it’s processed.
Solution to LeetCode 721: Accounts Merge Problem

You are given a list of accounts, where each account consists of a name and a list of emails. Merge accounts that share common emails, and return the merged accounts in the format: name followed by sorted emails.
Problem
Approach
Steps
Complexity
Input: Each account is represented by a list of strings. The first element is the name, and the rest are email addresses.
Example: accounts = [["Alice","alice@mail.com","alice_newyork@mail.com"], ["Alice","alice@mail.com","alice123@mail.com"], ["Bob","bob@mail.com"]]
Constraints:
• 1 <= accounts.length <= 1000
• 2 <= accounts[i].length <= 10
• 1 <= accounts[i][j].length <= 30
• accounts[i][0] consists of English letters.
• accounts[i][j] (for j > 0) is a valid email.
Output: Return the merged accounts, where each account starts with the name followed by a sorted list of email addresses.
Example: [["Alice","alice123@mail.com","alice@mail.com","alice_newyork@mail.com"]]
Constraints:
• The accounts should be returned with emails in sorted order and merged by shared emails.
Goal: The goal is to merge accounts based on common emails.
Steps:
• Use a graph where each email is a node, and there is an edge between two emails if they belong to the same account.
• For each account, build the graph by connecting emails together.
• Perform DFS (depth-first search) to find all connected emails for each component, representing one account.
• Sort the emails in lexicographical order and return the merged result with the name and emails.
Goal: Ensure the solution handles the problem within the provided constraints.
Steps:
• Ensure efficient handling of up to 1000 accounts with multiple emails.
Assumptions:
• Each account contains at least one email.
• The same person may have multiple accounts with the same or different names.
Input: accounts = [["Alice","alice@mail.com","alice_newyork@mail.com"], ["Alice","alice@mail.com","alice123@mail.com"], ["Bob","bob@mail.com"]]
Explanation: The first and second Alice accounts are merged since they share the email 'alice@mail.com'. The result should contain Alice’s emails sorted, and Bob’s account should remain unchanged.

Input: accounts = [["John","john1@mail.com","john2@mail.com","john3@mail.com"], ["Mike","mike1@mail.com","mike2@mail.com"], ["John","john1@mail.com","john4@mail.com"]]
Explanation: Both John accounts share 'john1@mail.com', so they are merged, with all of John’s emails sorted.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus