Skip to content

Commit 28f3f7a

Browse files
committed
Handle no-email accounts in account merge
1 parent 29137c9 commit 28f3f7a

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/main/java/com/thealgorithms/graph/AccountMerge.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff 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;

src/test/java/com/thealgorithms/graph/AccountMergeTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)