-
Notifications
You must be signed in to change notification settings - Fork 0
/
Making an anagram
40 lines (34 loc) · 1.17 KB
/
Making an anagram
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
Making Anagram- Find the minimum number of character deletions required to make the two strings anagrams.
We delete the following characters from our two strings to turn them into anagrams of each other:
Remove d and e from cde to get c.
Remove a and b from abc to get c.
We had to delete characters to make both strings anagrams.
Output:
'cde', 'abc' ==> 4
'absdjkvuahdakejfnfauhdsaavasdlkj', 'djfladfhiawasdkjvalskufhafablsdkashlahdfa' ==> 19
const createCharMap = (str) => {
const charMap = {};
for(let char of str){
if(charMap[char]){
charMap[char]++
} else {
charMap[char] = 1;
}
}
return charMap;
}
const makingAnagrams = (string1, string2) => {
const larger = string1.length >= string2.length ? string1 : string2;
const smaller = string1.length < string2.length ? string1 : string2;
const charMap = createCharMap(larger);
let counter = 0;
for(let char of smaller) {
if(charMap[char] && charMap[char] > 0) {
charMap[char]--;
counter++;
}
}
const diffOfSmaller = (smaller.length - counter);
const diffOfLarger = (larger.length - smaller.length);
return (2 * diffOfSmaller) + diffOfLarger;
}