Tensorum
LeetCode 721 · Union Find / DSU

Accounts Merge

LeetCode 721 · Medium · solution, intuition & step-by-step walkthrough

Union accounts sharing an email.

MediumArrayHash TableStringDepth-First SearchBreadth-First Search
10 msruntime · beats 100%
22.3 MBmemory · beats 74%
1approach
10accepted runs · last 29 Apr 2026

This is how I solved Accounts Merge (LeetCode 721), a medium problem from the Union Find / DSU pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Accounts that share an email belong to the same person. Map each email to the first account that had it; when another account has the same email, union the two accounts. Finally group emails by their account's root.

Approach

  1. 1

    email → first account index; union on repeats.

  2. 2

    Group each email under find(account).

  3. 3

    Output name + sorted emails per group.

How I solved it

Disjoint set unionPythonO(M α(N) + M log M)
class DisjointSet:
    def __init__(self,n):
        self.rank = [0]*(n+1)
        self.parents = [i for i in range(n+1)]
    def find(self,u):
        if self.parents[u]==u:
            return u
        self.parents[u]=self.find(self.parents[u])
        return self.parents[u]
    def union(self,u,v):
        pu,pv = self.find(u),self.find(v)
        if pu==pv:
            return
        if self.rank[pu]<self.rank[pv]:
            self.parents[pu]=pv
        elif self.rank[pv]<self.rank[pu]:
            self.parents[pv]=pu
        elif self.rank[pv]==self.rank[pu]:
            self.parents[pv]=pu 
            self.rank[pu]+=1

class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
        #account id - info 
        #email to account id mapping
        #if email is already there, connect them using disjoiint set

        #merge accounts
        #if email's final parent is same, add to the same account - parent account id, email

        #final response 
        #add name, email address
        n = len(accounts)
        if n==1:
            return accounts
        ds = DisjointSet(n)

        email_account_map = {}
        
        #M emails, N accounts
        #M*alpha(N)
        for u,account in enumerate(accounts): #M
            for email in account[1:]:
                if email in email_account_map: #alpha(N)
                     v = email_account_map[email] 
                     ds.union(u,v) 
                else:
                    email_account_map[email]=u
        
        merged_accunts = defaultdict(list)
        for email,account in email_account_map.items(): #O(M) - M unique emails
            ulp = ds.find(account) #O(alhpa(N))
            merged_accunts[ulp].append(email)
        res = []
        for account,emails in merged_accunts.items():
            name = accounts[account][0]
            res.append([name]+sorted(emails)) #MlogM
        return res

#Space Complexity - O(N) - for DSU
#Email Map - O(M)
#TC - O(M+N)

                 
Loading the step-through…

Accounts Merge — FAQ

What is the intuition behind Accounts Merge?

Accounts that share an email belong to the same person. Map each email to the first account that had it; when another account has the same email, union the two accounts. Finally group emails by their account's root.

How do you solve Accounts Merge (LeetCode 721)?

1. email → first account index; union on repeats. 2. Group each email under find(account). 3. Output name + sorted emails per group.

What is the time and space complexity of Accounts Merge?

Time: O(M log M). Space: O(M + N). (Accepted approach: Disjoint set union.)

What are common mistakes in Accounts Merge?

Names can repeat across different people — only shared emails merge accounts.