Talentd
FleetCode
Make and follow sheets.Sign in

Accounts Merge solution and explanation

MediumArrayBreadth-First SearchDepth-First SearchHash Table7 min read62.2% acceptanceUpdated 9 Apr 2026
G-50. Accounts Merge - DSUtake U forward · 22:01 · 213K viewsWatch on YouTube
9 more videos on this problem
  1. G-50. Accounts Merge - DSUtake U forward · 22:01 · 213K views
  2. Accounts Merge - Leetcode 721 - PythonNeetCodeIO · 17:13 · 68K views
  3. LeetCode 721. Accounts Merge [Coding Interview Solution Explained]Shiran Afergan · 14:30 · 22K views
  4. ACCOUNTS MERGE | LEETCODE # 721 | PYTHON SOLUTIONCracking FAANG · 23:04 · 18K views
  5. LeetCode 721. Accounts Merge Explanation and Solutionhappygirlzt · 11:40 · 15K views
  6. LeetCode 721. Accounts MergeHappy Coding · 18:56 · 7K views
  7. LeetCode Solutions | 721 | Accounts MergeRahul Manghnani · 30:11 · 6K views
  8. Google Coding Interview Question | Leetcode 721 | Accounts MergeWorkWithGoogler · 33:37 · 3K views
  9. Accounts Merge | LeetCode | DSU/UF Solution Explained in DetailTanishq Chaudhary · 14:31 · 2K views
  10. Daily Leetcode #608: Nov 29, 2021 - 721. Accounts MergeProgramming Live with Larry · 14:32 · 689 views

The problem

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.

Example 1:

Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Explanation:
The first and second John's are the same person as they have the common email "johnsmith@mail.com".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], 
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.

Example 2:

Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]

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.

Approach overview

Problem Overview: You receive a list of user accounts where each entry contains a name followed by multiple email addresses. Two accounts belong to the same person if they share at least one common email. The task is to merge such accounts and return the consolidated list with unique emails sorted lexicographically.

Approach 1: Graph-Based Approach (DFS/BFS) (Time: O(E log E), Space: O(E))

Treat each email as a node in a graph. If two emails appear in the same account, connect them with an edge. This creates connected components where all emails in the same component belong to the same user. Build an adjacency list using a hash table, then run DFS or BFS from each unvisited email to collect all reachable emails in that component. Track the account name associated with each email during construction. After collecting a component, sort the emails before adding them to the result. The key insight is that shared emails create graph connectivity, so the merge problem becomes a connected-components problem.

Approach 2: Union-Find Approach (Disjoint Set) (Time: O(E log E), Space: O(E))

Use a Union-Find data structure to group emails belonging to the same person. Iterate through each account and union the first email with every other email in that account. Maintain a parent mapping for each email and apply path compression to keep operations nearly constant time. After processing all unions, group emails by their root parent using a hash map. Each group represents a merged account. Sort the emails in each group and prepend the corresponding user name. This approach avoids explicit graph traversal and is often cleaner for connectivity problems.

Recommended for interviews: The Union-Find approach is typically preferred because it models the merging operation directly and scales well when many accounts share emails. The graph approach demonstrates strong understanding of connected components using DFS or BFS, which interviewers also value. Showing the graph interpretation first and then optimizing with Union-Find demonstrates solid problem-solving depth.

Approach 1: Graph-Based Approach

In this approach, we treat each email as a node in a graph and create edges between nodes that appear in the same account. By doing so, connected components in the graph will represent emails belonging to the same person.

Once the graph is constructed, we perform a Depth-First Search (DFS) to enumerate all emails in each connected component, sort the collected emails, and then append the owner’s name to produce the final result.

from collections import defaultdict

def accountsMerge(accounts):
    email_graph = defaultdict(set)
    email_to_name = {}

    for account in accounts:
        name = account[0]
        emails = account[1:]
        first_email = emails[0]

        for email in emails:
            email_graph[first_email].add(email)
            email_graph[email].add(first_email)
            email_to_name[email] = name

    visited = set()
    def dfs(email):
        visited.add(email)
        component = [email]
        for neighbor in email_graph[email]:
            if neighbor not in visited:
                component.extend(dfs(neighbor))
        return component

    output = []
    for email in email_graph:
        if email not in visited:
            connected_emails = dfs(email)
            output.append([email_to_name[email]] + sorted(connected_emails))

    return output
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <string>
using namespace std;

void dfs(const string &email, unordered_map<string, unordered_set<string>> &emailGraph,
         unordered_set<string> &visited, vector<string> &component) {
    visited.insert(email);
    component.push_back(email);
    for (const string &neighbor : emailGraph[email]) {
        if (!visited.count(neighbor)) {
            dfs(neighbor, emailGraph, visited, component);
        }
    }
}

vector<vector<string>> accountsMerge(vector<vector<string>> &accounts) {
    unordered_map<string, unordered_set<string>> emailGraph;
    unordered_map<string, string> emailToName;

    // Build the graph
    for (const auto &account : accounts) {
        const string &name = account[0];
        for (int j = 1; j < account.size(); ++j) {
            emailGraph[account[1]].insert(account[j]);
            emailGraph[account[j]].insert(account[1]);
            emailToName[account[j]] = name;
        }
    }

    // DFS to find connected components
    unordered_set<string> visited;
    vector<vector<string>> result;
    for (const auto &pair : emailGraph) {
        const string &email = pair.first;
        if (!visited.count(email)) {
            vector<string> component;
            dfs(email, emailGraph, visited, component);
            sort(component.begin(), component.end());
            component.insert(component.begin(), emailToName[email]);
            result.push_back(component);
        }
    }
    return result;
}

The Python solution uses a dictionary to map emails to a graph structure. Each email is treated as a node, and accounts describe connections. We apply a depth-first search to explore connected components and collect emails of each component. Each collection is sorted and paired with the account owner’s name before appending to the result list.

Complexity

Time complexity is O(NK log NK), where N is the number of accounts, and K is the maximum number of emails in an account, due to sorting each component. Space complexity is O(NK) for storing the graph and visited nodes.

Try this approach in the editor

Approach 2: Union-Find Approach

This approach uses a Union-Find data structure for efficient merging of accounts. Each email is identified with a parent, initially itself, and accounts are unified if they share an email. We then deduce separate email sets from parent-child relationships.

import java.util.*;

public class Solution {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        Map<String, String> emailToName = new HashMap<>();
        Map<String, String> parent = new HashMap<>();
        for (List<String> account : accounts) {
            String name = account.get(0);
            for (int i = 1; i < account.size(); i++) {
                emailToName.put(account.get(i), name);
                parent.put(account.get(i), account.get(i));
            }
        }

        for (List<String> account : accounts) {
            String p = find(account.get(1), parent);
            for (int i = 2; i < account.size(); i++) {
                parent.put(find(account.get(i), parent), p);
            }
        }

        Map<String, TreeSet<String>> unions = new HashMap<>();
        for (List<String> account : accounts) {
            for (int i = 1; i < account.size(); i++) {
                String root = find(account.get(i), parent);
                unions.computeIfAbsent(root, x -> new TreeSet<>()).add(account.get(i));
            }
        }

        List<List<String>> result = new ArrayList<>();
        for (String root : unions.keySet()) {
            List<String> emails = new ArrayList<>(unions.get(root));
            emails.add(0, emailToName.get(root));
            result.add(emails);
        }
        return result;
    }

    private String find(String s, Map<String, String> parent) {
        return parent.get(s) == s ? s : find(parent.get(s), parent);
    }
}
var accountsMerge = function(accounts) {
    const emailToName = {};
    const parent = {};
    const find = (x) => parent[x] !== x ? parent[x] = find(parent[x]) : x;

    for (const acc of accounts) {
        for (let i = 1; i < acc.length; i++) {
            parent[acc[i]] = acc[i];
            emailToName[acc[i]] = acc[0];
        }
    }

    for (const acc of accounts) {
        const p = find(acc[1]);
        for (let i = 2; i < acc.length; i++) {
            parent[find(acc[i])] = p;
        }
    }

    const unions = {};
    for (const acc of accounts) {
        for (let i = 1; i < acc.length; i++) {
            const root = find(acc[i]);
            if (!unions[root]) unions[root] = new Set();
            unions[root].add(acc[i]);
        }
    }

    const result = [];
    for (const root in unions) {
        const emails = Array.from(unions[root]).sort();
        emails.unshift(emailToName[root]);
        result.push(emails);
    }

    return result;
};

In the Java solution, Union-Find is used to connect and find associated emails. We first store each email with its own parent, then use the find operation to determine shared components. Finally, a mapping between connected components and their parent node helps in gathering and sorting emails accordingly.

Complexity

Time complexity is O(NK log NK) due to sorting each email list. Space complexity is O(NK) owing to email mappings and Union-Find arrangements.

Try this approach in the editor

Approach 3: Union-Find + Hash Table

Based on the problem description, we can use a union-find data structure to merge accounts with the same email address. The specific steps are as follows:

First, we iterate through all the accounts. For the ith account, we iterate through all its email addresses. If an email address appears in the hash table d, we use the union-find to merge the account's index i with the previously appeared account's index; otherwise, we map this email address to the account's index i.

Next, we iterate through all the accounts again. For the ith account, we use the union-find to find its root node, and then add all the email addresses of that account to the hash table g, where the key is the root node, and the value is the account's email addresses.

The time complexity is O(n times log n), and the space complexity is O(n). Here, n is the number of accounts.

class UnionFind {
    private p: number[];
    private size: number[];

    constructor(n: number) {
        this.p = new Array(n);
        this.size = new Array(n);
        for (let i = 0; i < n; ++i) {
            this.p[i] = i;
            this.size[i] = 1;
        }
    }

    find(x: number): number {
        if (this.p[x] !== x) {
            this.p[x] = this.find(this.p[x]);
        }
        return this.p[x];
    }

    union(a: number, b: number): boolean {
        let pa = this.find(a),
            pb = this.find(b);
        if (pa === pb) {
            return false;
        }
        if (this.size[pa] > this.size[pb]) {
            this.p[pb] = pa;
            this.size[pa] += this.size[pb];
        } else {
            this.p[pa] = pb;
            this.size[pb] += this.size[pa];
        }
        return true;
    }
}

function accountsMerge(accounts: string[][]): string[][] {
    const n = accounts.length;
    const uf = new UnionFind(n);
    const d = new Map<string, number>();

    for (let i = 0; i < n; ++i) {
        for (let j = 1; j < accounts[i].length; ++j) {
            const email = accounts[i][j];
            if (d.has(email)) {
                uf.union(i, d.get(email)!);
            } else {
                d.set(email, i);
            }
        }
    }

    const g = new Map<number, Set<string>>();
    for (let i = 0; i < n; ++i) {
        const root = uf.find(i);
        if (!g.has(root)) {
            g.set(root, new Set<string>());
        }
        const emailSet = g.get(root)!;
        for (let j = 1; j < accounts[i].length; ++j) {
            emailSet.add(accounts[i][j]);
        }
    }

    const ans: string[][] = [];
    for (const [root, emails] of g.entries()) {
        const emailList = Array.from(emails).sort();
        const mergedAccount = [accounts[root][0], ...emailList];
        ans.push(mergedAccount);
    }

    return ans;
}
type unionFind struct {
	p, size []int
}

func newUnionFind(n int) *unionFind {
	p := make([]int, n)
	size := make([]int, n)
	for i := range p {
		p[i] = i
		size[i] = 1
	}
	return &unionFind{p, size}
}

func (uf *unionFind) find(x int) int {
	if uf.p[x] != x {
		uf.p[x] = uf.find(uf.p[x])
	}
	return uf.p[x]
}

func (uf *unionFind) union(a, b int) bool {
	pa, pb := uf.find(a), uf.find(b)
	if pa == pb {
		return false
	}
	if uf.size[pa] > uf.size[pb] {
		uf.p[pb] = pa
		uf.size[pa] += uf.size[pb]
	} else {
		uf.p[pa] = pb
		uf.size[pb] += uf.size[pa]
	}
	return true
}

func accountsMerge(accounts [][]string) (ans [][]string) {
	n := len(accounts)
	uf := newUnionFind(n)
	d := make(map[string]int)
	for i := 0; i < n; i++ {
		for _, email := range accounts[i][1:] {
			if j, ok := d[email]; ok {
				uf.union(i, j)
			} else {
				d[email] = i
			}
		}
	}
	g := make(map[int]map[string]struct{})
	for i := 0; i < n; i++ {
		root := uf.find(i)
		if _, ok := g[root]; !ok {
			g[root] = make(map[string]struct{})
		}
		for _, email := range accounts[i][1:] {
			g[root][email] = struct{}{}
		}
	}
	for root, s := range g {
		emails := []string{}
		for email := range s {
			emails = append(emails, email)
		}
		sort.Strings(emails)
		account := append([]string{accounts[root][0]}, emails...)
		ans = append(ans, account)
	}
	return
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Graph-Based Approach

Time complexity is O(NK log NK), where N is the number of accounts, and K is the maximum number of emails in an account, due to sorting each component. Space complexity is O(NK) for storing the graph and visited nodes.

Union-Find Approach

Time complexity is O(NK log NK) due to sorting each email list. Space complexity is O(NK) owing to email mappings and Union-Find arrangements.

Union-Find + Hash Table–

Complexity analysis

ApproachTimeSpaceWhen to Use
Graph Traversal (DFS/BFS)O(E log E)O(E)When modeling the problem as connected components in a graph and using DFS/BFS is more intuitive
Union-Find (Disjoint Set)O(E log E)O(E)Best general solution for merging sets with shared identifiers like emails

Frequently asked questions

Is Accounts Merge easy or hard?

Accounts Merge is considered a Medium difficulty problem. The challenge comes from recognizing that shared emails create connectivity between accounts and choosing the right technique such as DFS graph traversal or the Union-Find data structure.

Accounts Merge Python/Java solution

Python solutions usually build an adjacency list with dictionaries and run DFS to collect connected emails, or implement Union-Find using dictionaries. Java solutions commonly use HashMap with a Disjoint Set class to union emails and group them by root parent before sorting.

How to solve Accounts Merge in O(n)?

Pure O(n) is difficult because the output requires emails to be sorted. The merging step using Union-Find or DFS can run in near O(E) time, but sorting the emails in each merged account results in an overall complexity of O(E log E).

What is the best approach for Accounts Merge?

The Union-Find (Disjoint Set) approach is generally the best solution. It efficiently groups emails that belong to the same person by unioning emails within the same account and later collecting them by root parent. With path compression, union and find operations are nearly constant time, and the overall complexity is dominated by sorting emails, giving O(E log E).

Is Accounts Merge asked at Google/Amazon/Meta?

Accounts Merge is a common interview-style problem involving graph connectivity and Union-Find. Variants of this problem have appeared in interviews at companies like Google, Amazon, and Meta because it tests understanding of disjoint sets, hashing, and graph traversal.

What data structure is used in Accounts Merge?

The most important data structures are hash maps and Union-Find (Disjoint Set). Hash maps map emails to owners or adjacency lists, while Union-Find efficiently groups connected emails. Graph representations with DFS or BFS are also widely used.

What is the time complexity of Accounts Merge?

The overall time complexity is O(E log E), where E is the total number of unique emails. Building connections using Union-Find or a graph traversal takes near linear time, while sorting the emails in each merged account contributes the log factor.

Comments

Now write it yourselfClose this page and solve Accounts Merge in the editor, without looking.
Practise Accounts Merge