Skip to content

Commit f9db792

Browse files
committed
✨ [mock] Added solution without logs
1 parent fe0b862 commit f9db792

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
const processAlmostAnagramPair = (list) => {
2+
let result = new Map();
3+
4+
for (let i = 0; i < list.length; i++) {
5+
for (let k = 0; k < list.length; k++) {
6+
if (i !== k) { // Ignore the same node
7+
let curr = list[i];
8+
result.set(curr,
9+
(result.has(curr) ? result.get(curr) : 0) + (isAlmostAnagram(curr, list[k]) ? 1 : 0))
10+
}
11+
}
12+
}
13+
14+
return result;
15+
}
16+
17+
const isAlmostAnagram = (item1, item2) => {
18+
if (item1.length !== item2.length) return null;
19+
20+
let char = item1.split(""), count = 0;
21+
let map1 = createMap(item1), map2 = createMap(item2);
22+
23+
for (let i = 0; i < char.length; i++) {
24+
// Here is a trick, as long as they have the same value AND ONLY if both of them have values (appeared) more than 0.
25+
// As we are doing deduction below - this is to handle cases like repeating character.
26+
if ((map1.has(char[i]) && map2.has(char[i]))
27+
&& (0 < map1.get(char[i])
28+
&& 0 < map2.get(char[i]))
29+
) {
30+
map1.set(char[i], map1.get(char[i]) - 1)
31+
map2.set(char[i], map2.get(char[i]) - 1)
32+
count++;
33+
}
34+
}
35+
36+
// Almost anagram => -1 | 1 word different
37+
return (1 === (char.length - count));
38+
}
39+
40+
const createMap = (item) => {
41+
let map = new Map();
42+
if (undefined === item) return map;
43+
44+
let char = item.split("");
45+
46+
for (let i = 0; i < char.length; i++) {
47+
map.set(char[i], ((map.has(char[i])) ? map.get(char[i]) : 0) + 1)
48+
}
49+
50+
return map;
51+
}
52+
53+
processAlmostAnagramPair(["race", "beat", "brass", "grass", "sabre", "back", "chat", "cabs", "saga", "pack"]);

0 commit comments

Comments
 (0)