File tree Expand file tree Collapse file tree 2 files changed +25
-0
lines changed
main/java/com/thealgorithms/graph
test/java/com/thealgorithms/graph Expand file tree Collapse file tree 2 files changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -41,6 +41,12 @@ public static List<List<String>> mergeAccounts(List<List<String>> accounts) {
4141 int root = dsu .find (entry .getValue ());
4242 rootToEmails .computeIfAbsent (root , ignored -> new ArrayList <>()).add (entry .getKey ());
4343 }
44+ for (int i = 0 ; i < accounts .size (); i ++) {
45+ if (accounts .get (i ).size () <= 1 ) {
46+ int root = dsu .find (i );
47+ rootToEmails .computeIfAbsent (root , ignored -> new ArrayList <>());
48+ }
49+ }
4450
4551 List <List <String >> merged = new ArrayList <>();
4652 for (Map .Entry <Integer , List <String >> entry : rootToEmails .entrySet ()) {
@@ -59,6 +65,9 @@ public static List<List<String>> mergeAccounts(List<List<String>> accounts) {
5965 if (cmp != 0 ) {
6066 return cmp ;
6167 }
68+ if (a .size () == 1 || b .size () == 1 ) {
69+ return Integer .compare (a .size (), b .size ());
70+ }
6271 return a .get (1 ).compareTo (b .get (1 ));
6372 });
6473 return merged ;
Original file line number Diff line number Diff line change @@ -63,4 +63,20 @@ void testTransitiveMergeAndDuplicateEmails() {
6363
6464 assertEquals (expected , merged );
6565 }
66+
67+ @ Test
68+ void testAccountsWithNoEmailsArePreserved () {
69+ List <List <String >> accounts = List .of (
70+ List .of ("Alex" ),
71+ List .of ("Alex" , "alex1@mail.com" ),
72+ List .of ("Bob" ));
73+
74+ List <List <String >> merged = AccountMerge .mergeAccounts (accounts );
75+ List <List <String >> expected = List .of (
76+ List .of ("Alex" ),
77+ List .of ("Alex" , "alex1@mail.com" ),
78+ List .of ("Bob" ));
79+
80+ assertEquals (expected , merged );
81+ }
6682}
You can’t perform that action at this time.
0 commit comments