Imagine you're working at a tech company where employees can have multiple email accounts, but sometimes they create duplicate profiles in your system. Your task is to merge accounts that belong to the same person by identifying shared email addresses.
Given a list of accounts where each account contains:
First element: name (string)
Remaining elements: emails associated with that account
The Challenge: Two accounts belong to the same person if they share at least one email address. Even accounts with the same name might belong to different people, but accounts belonging to the same person will always have the same name.
Your Goal: Return merged accounts where:
First element is the person's name
Remaining elements are all their emails in sorted order
💡 Note:The first and second John accounts share '[email protected]', so they merge. The third John has no shared emails with others, so stays separate. Mary remains unchanged.
f
Facebook 45G
Google 38a
Amazon 32⊞
Microsoft 28
Apple 15
Accounts Merge — Solution
The optimal solution uses Union-Find (Disjoint Set Union) to efficiently group accounts that share emails. We map each email to its first occurrence, then union accounts that share emails. Finally, we group accounts by their root parent and merge all emails in each group, returning them sorted. Time complexity: O(n × m × α(n)) where α is the inverse Ackermann function.
Common Approaches
✓
Brute Force (Graph Building)
⏱️ Time: O(n² × m²)
Space: O(n × m)
Create a graph where each account is connected to other accounts that share at least one email. Then use DFS to find all connected components (groups of accounts belonging to the same person).
Union-Find (Disjoint Set Union)
⏱️ Time: O(n × m × α(n))
Space: O(n × m)
Map each email to its first occurrence, then use Union-Find to group accounts. This avoids the expensive pairwise comparison of the brute force approach by leveraging the fact that if accounts A and B share an email, and accounts B and C share an email, then A and C are also connected.
Brute Force (Graph Building) — Algorithm Steps
Build a graph by comparing each account with every other account
Connect accounts that share at least one email and have the same name
Use DFS to find connected components
For each component, collect all unique emails and sort them
Return merged accounts with name and sorted emails
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Build Graph
Connect accounts that share emails and have same name
2
DFS Traversal
Find connected components using depth-first search
3
Merge Accounts
Collect all emails in each component and sort them
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ACCOUNTS 1000
#define MAX_EMAILS 10
#define MAX_EMAIL_LEN 31
#define MAX_NAME_LEN 31
#define MAX_INPUT 10000
typedef struct {
char emails[MAX_EMAILS * MAX_ACCOUNTS][MAX_EMAIL_LEN];
int emailCount;
} EmailSet;
typedef struct {
int connections[MAX_ACCOUNTS];
int count;
} AdjList;
static int visited[MAX_ACCOUNTS];
static AdjList graph[MAX_ACCOUNTS];
static EmailSet componentEmails;
void dfs(int accountIdx, char*** accounts, int* accountsColSize) {
visited[accountIdx] = 1;
for (int i = 1; i < accountsColSize[accountIdx]; i++) {
strcpy(componentEmails.emails[componentEmails.emailCount], accounts[accountIdx][i]);
componentEmails.emailCount++;
}
for (int i = 0; i < graph[accountIdx].count; i++) {
int neighbor = graph[accountIdx].connections[i];
if (!visited[neighbor]) {
dfs(neighbor, accounts, accountsColSize);
}
}
}
void removeDuplicates(EmailSet* set) {
int newCount = 0;
for (int i = 0; i < set->emailCount; i++) {
int isDuplicate = 0;
for (int j = 0; j < newCount; j++) {
if (strcmp(set->emails[i], set->emails[j]) == 0) {
isDuplicate = 1;
break;
}
}
if (!isDuplicate) {
if (i != newCount) {
strcpy(set->emails[newCount], set->emails[i]);
}
newCount++;
}
}
set->emailCount = newCount;
}
int compareEmails(const void* a, const void* b) {
return strcmp((const char*)a, (const char*)b);
}
char*** parseInput(char* input, int* accountsSize, int** accountsColSize) {
char*** accounts = (char***)malloc(MAX_ACCOUNTS * sizeof(char**));
*accountsColSize = (int*)malloc(MAX_ACCOUNTS * sizeof(int));
*accountsSize = 0;
char* ptr = input + 2; // Skip initial [[
while (*ptr && *ptr != '\n') {
if (*accountsSize >= MAX_ACCOUNTS) break;
accounts[*accountsSize] = (char**)malloc(MAX_EMAILS * sizeof(char*));
(*accountsColSize)[*accountsSize] = 0;
while (*ptr && *ptr != ']') {
if (*ptr == '"') {
ptr++; // Skip opening quote
char* start = ptr;
while (*ptr && *ptr != '"') ptr++;
int len = ptr - start;
accounts[*accountsSize][(*accountsColSize)[*accountsSize]] = (char*)malloc((len + 1) * sizeof(char));
strncpy(accounts[*accountsSize][(*accountsColSize)[*accountsSize]], start, len);
accounts[*accountsSize][(*accountsColSize)[*accountsSize]][len] = '\0';
(*accountsColSize)[*accountsSize]++;
if (*ptr == '"') ptr++; // Skip closing quote
} else {
ptr++;
}
}
if (*ptr == ']') ptr++; // Skip ]
while (*ptr && (*ptr == ',' || *ptr == '[' || *ptr == ' ')) ptr++; // Skip separators
(*accountsSize)++;
if (*ptr == ']') break; // End of input
}
return accounts;
}
int main() {
static char input[MAX_INPUT];
fgets(input, MAX_INPUT, stdin);
int accountsSize;
int* accountsColSize;
char*** accounts = parseInput(input, &accountsSize, &accountsColSize);
// Initialize graph
for (int i = 0; i < accountsSize; i++) {
graph[i].count = 0;
visited[i] = 0;
}
// Build graph - connect accounts that share emails and have same name
for (int i = 0; i < accountsSize; i++) {
for (int j = i + 1; j < accountsSize; j++) {
if (strcmp(accounts[i][0], accounts[j][0]) == 0) {
int hasCommon = 0;
for (int ei = 1; ei < accountsColSize[i] && !hasCommon; ei++) {
for (int ej = 1; ej < accountsColSize[j]; ej++) {
if (strcmp(accounts[i][ei], accounts[j][ej]) == 0) {
hasCommon = 1;
break;
}
}
}
if (hasCommon) {
graph[i].connections[graph[i].count++] = j;
graph[j].connections[graph[j].count++] = i;
}
}
}
}
printf("[");
int resultCount = 0;
for (int i = 0; i < accountsSize; i++) {
if (!visited[i]) {
componentEmails.emailCount = 0;
dfs(i, accounts, accountsColSize);
removeDuplicates(&componentEmails);
qsort(componentEmails.emails, componentEmails.emailCount, MAX_EMAIL_LEN, compareEmails);
if (resultCount > 0) printf(",");
printf("[\"%s\"", accounts[i][0]);
for (int j = 0; j < componentEmails.emailCount; j++) {
printf(",\"%s\"", componentEmails.emails[j]);
}
printf("]");
resultCount++;
}
}
printf("]\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n² × m²)
n accounts, each comparison takes O(m²) where m is max emails per account
n
2n
⚠ Quadratic Growth
Space Complexity
O(n × m)
Store graph adjacency list and visited arrays
n
2n
⚡ Linearithmic Space
125.1K Views
HighFrequency
~25 minAvg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.