-
Notifications
You must be signed in to change notification settings - Fork 3
/
making-anagrams.js
48 lines (37 loc) · 1.3 KB
/
making-anagrams.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* @title Making Anagrams
* @difficulty Easy
* @link https://www.hackerrank.com/challenges/making-anagrams/problem
*/
const makingAnagrams = (strA, strB) => {
const strACountMap = createCountMapFromString(strA);
const strBCountMap = createCountMapFromString(strB);
return getEntriesDistanceSum(strACountMap, strBCountMap);
};
const createCountMapFromString = str => (
[...str].reduce((map, char) => {
const count = map.has(char) ? map.get(char) + 1 : 1;
map.set(char, count);
return map;
}, new Map())
);
const getEntriesDistanceSum = (mapA, mapB) => {
const setA = new Set([...mapA.keys()]);
const setB = new Set([...mapB.keys()]);
const intersectionSum =
getIntersectionEntries(setA, setB)
.reduce((sum, char) => sum + Math.abs(mapA.get(char) - mapB.get(char)), 0);
const differenceASum =
getDifferenceEntries(setA, setB)
.reduce((sum, char) => sum + mapA.get(char), 0);
const differenceBSum =
getDifferenceEntries(setB, setA)
.reduce((sum, char) => sum + mapB.get(char), 0);
return intersectionSum + differenceASum + differenceBSum;
};
const getIntersectionEntries = (setA, setB) => [
...new Set([...setA].filter(key => setB.has(key)))
];
const getDifferenceEntries = (setA, setB) => [
...new Set([...setA].filter(key => !setB.has(key)))
];