Accounts Merge
Problem Statement
You get a list of accounts. Each account is a list of strings: the first string is the owner's name, and the rest are the emails on that account.
Two accounts belong to the same person when they share at least one email. The rule chains: if A shares an email with B, and B shares one with C, then A, B and C are all one person. Two accounts with the same name can still be different people.
Merge the accounts that belong to one person. Each merged account is the name, followed by all of that person's emails in sorted order. Return the merged accounts in any order.
accounts: a list of accounts. Each account is [name, email1, email2, ...].
A list of merged accounts. Each one is [name, sorted emails...]. The order of the accounts in the answer does not matter.
The first two Johns share johnsmith@mail.com, so they are one person. The third John shares no email with anyone, so he stays separate, even though the name is the same.
The two accounts share b@m.co, so they merge into one account with three sorted emails.
- • 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
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Repeatedly merge any two groups that share an email, rescanning after each merge
Give each email an id, union within each account, group emails by root, then sort
Start with one group per account. Find any two groups that share an email, merge them, and rescan from the start. When a full scan finds no pair to merge, the groups are final: sort each group's emails and put the name first.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Union-Find (DSU) translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.