AlgoMaster Logo

Accounts Merge

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. DFS and HashMap

Intuition:

The task is essentially about grouping connected components (emails) under the same owner. Using DFS, we can find all connected components (i.e., all emails linked to each other) and finally concatenate the results under the same account.

  1. Use a map to associate each email with its owner and build a graph connecting these emails.
  2. Apply DFS to traverse through the graph, marking each email visited and gathering all connected emails (representing one complete account).
  3. For each account's first email, perform DFS to fetch all connected emails, sort them, and store under the corresponding owner.

Code:

2. Union Find

Intuition:

Union-Find (Disjoint Set Union) is a perfect fit for grouping connected components and is typically used in problems of this pattern. We can take advantage of it to union all emails under the same account and later find and collect emails by their root (or parent).

  1. Initialize Union-Find structures and map each email to its parent.
  2. Union emails and organize them, setting their first email as the "parent".
  3. Use a Map to group emails by their parents/components.
  4. Append sorted grouped emails, prefixed by their owner's name, to the result list.

Code: