Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Accounts Merge

Hard
0/120
Average time to solve is 15m
18 upvotes
Asked in companies
Phone PeAmazonFacebook

Problem statement

You have been given an array/list 'accounts' where each element, i.e. 'accounts'[i] contains a list of strings.


In 'accounts'[i], the first element is the name of the account holder, and the rest of the strings are emails representing the emails of the account.


Now, you are supposed to merge the accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that it may be possible that two accounts belong to the same name, but they may belong to different people, as people could have the same name.


A person could have any number of accounts initially, but all their accounts definitely have the same name.


After merging the accounts, you have to return an array/list of merged accounts where each account, the first element is the person's name, and the rest elements are the email addresses in sorted order (non-decreasing). Accounts themselves can be in any order.


Example:
 Input:  'n' = 4,
 'accounts' = [
    ["Rohan", "rohan123@gmail.com", "1279ro@gmail.com"],
    ["Rohit", "rohit101@yahoo.com", "hitman30487@gmail.com"],
    ["Rohan", "1279ro@gmail.com",  "niemann01@gmail.com"],
    ["Rohan", "kaushik@outlook.com"],
 ]
 Output: [
    ["Rohan", "rohan123@gmail.com", "1279ro@gmail.com", "niemann01@gmail.com"],
    ["Rohit", "rohit101@yahoo.com", "hitman30487@gmail.com"],
    ["Rohan", "kaushik@outlook.com"],
 ]

 Explanation: The first and third "Rohan" are the same person as they have a shared email address, “1279ro@gmail.com”. The rest of the accounts are of different persons, as they don’t share any shared email addresses. So, we merge the first and third accounts.
Detailed explanation ( Input/output format, Notes, Images )
Sample Input 1 :
4
3 Rahul rahul1@gmail.com rahul2@gmail.com 
2 Amit amit1@gmail.com
2 Ankur ankur9773@yahoo.com
3 Rahul rahul1@gmail.com rahul1998@yahoo.com
Sample output 1 :
3
Amit amit1@gmail.com 
Ankur ankur9773@gmail.com 
Rahul rahul1998@yahoo.com rahul1@gmail.com rahul2@gmail.com 
Explanation of Sample Input 1 :
The first and fourth "Rahul" are the same person as they have a shared email address, “rahul1@gmail.com”. The rest of the accounts are of different persons, as they don’t share any shared email addresses. So, we merge the first and fourth accounts.
Sample Input 2 :
2
2 Atul atul@mail.com
2 Atul atul1@mail.com
Sample output 2 :
2
Atul atul1@mail.com 
Atul atul@mail.com 
Explanation of Sample Input 2 :
The first and second Atul are two different people since they don’t have any common email addresses.
Constraints :
1 <= 'n' <= 5000
1 <= |'accounts'[i]| <= 10
1 <= |'accounts'[i][j]| <= 30

Time limit: 1 sec
Full screen
Console