Merging Accounts Problem

Given a list ACCOUNTS where each element consists of a list of strings, with the first element being the name of the account holder, and the subsequent elements being the email addresses associated with that account, your task is to merge accounts.

Merge accounts belonging to the same person if there is any email address common to both accounts. Be aware that accounts having the same name could belong to different individuals, and a single individual may have multiple accounts, but all such accounts will have the same name.

After merging, return a list of accounts where each element contains the account holder's name followed by a non-decreasing sorted list of their email addresses. The overall order of merged accounts does not matter.

Input:

int T - representing the number of test cases.
For each test case:
int N - number of accounts.
List of N lines, each containing space-separated strings:
First string: name
Remaining strings: emails

Output:

For each test case:
int - number of merged accounts
Each subsequent line contains:
space-separated name and sorted email addresses.

Example:

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"

Constraints:

  • 1 <= T <= 50
  • 1 <= N <= 100
  • 1 <= |accounts[i]| <= 10
  • 1 <= |accounts[i][j]| <= 30

Time limit: 1 second

Note:

Implementation of the function is required; no output is needed as printing has been managed.
AnswerBot
1y

The task is to merge accounts belonging to the same person based on common emails and return the merged accounts.

  • Iterate through each account and create a mapping of emails to account holders

  • Iterate t...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Facebook

Q. How does Facebook store likes and dislikes?
Q. How does Facebook implement graph search?
Q. How does Facebook Chat work?
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits