Accounts Merge
MST & Disjoint Set DSA practice problem on Onlearn.
Difficulty: hard.
Topics: Merging Accounts with Common Emails Using Disjoint Set, Disjoint Set Union, Union by Rank, Union by Size, Path Compression, Hash Map, Sorting, Time Complexity, Space Complexity, Graph, Connected Components, complexity analysis, union-find, merging algorithms, sorting algorithms, hash map, Disjoint Set Union (DSU) / Union-Find, DSU Applications.
Problem Statement Given a list of accounts accounts, where each accounts[i] is a list of strings. The first element accounts[i][0] is a name, and the rest are emails associated with that account. The task is to merge these accounts. Two accounts definitely belong to the same person if there is at least one common email between them. 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 will have the same name. After merging the accounts, return the merged accounts in the following format: the first element of each account must be the name, followed by all merged emails in lexicographically sorted order. The order of the merged accounts themselves does not matter. Input accounts: A list of lists of strings, where accounts[i][0] is a name and accounts[i][1:] are emails. Output A list of merged accounts. Each merged account starts with the name, followed by all unique merged emails in lexicographically sorted order. The order of merged accounts in the final list does not matter. Examples 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 the second "John" accounts are merged because they share "johnsmith@mail.com". The "Mary" and the fourth "John" accounts remain separate as they have no common emails. Emails within each merged account are sorted alphabetically. Example 2: Input: accounts = [["John","j1@com","j2@com","j3@com"], ["John","j4@com"], ["Raj","r1@com","r2@com"], ["John","j1@com","j5@com"], ["Raj","r2@com","r3@com"], ["Mary","m1@com"]] Output: [["John","j1@com","j2@com","j3@com","j5@com"], ["John","j4@com"], ["Raj","r1@com","r2@com","r3@com"], ["Mary","m1@com"]] Explanation: The first and fourth "John" accounts are merged due to "j1@com". The third and fifth "Raj" accounts are merged due to "r2@com". The other accounts remain separate.