Created
January 25, 2017 23:43
-
-
Save jasonwaters/99d0a480e0935b8daa71f3c278dbfda5 to your computer and use it in GitHub Desktop.
anagram removals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any characters can be deleted from either of the strings. | |
| https://www.hackerrank.com/challenges/ctci-making-anagrams | |
| */ | |
| function indexChars(map, char) { | |
| if(!map.hasOwnProperty(char)) { | |
| map[char] = 0; | |
| } | |
| map[char]++; | |
| return map; | |
| } | |
| function findRemovals(mapA, mapB) { | |
| let removals = 0; | |
| for(let key in mapA) { | |
| let diff = Math.abs((mapA[key] || 0) - (mapB[key] || 0)); | |
| removals += diff; | |
| if(diff > 0) { | |
| delete mapB[key]; | |
| } | |
| } | |
| return removals; | |
| } | |
| function anagram(strA, strB) { | |
| let mapA = strA.split('').reduce(indexChars, {}); | |
| let mapB = strB.split('').reduce(indexChars, {}); | |
| let removals = 0; | |
| removals += findRemovals(mapA, mapB); | |
| removals += findRemovals(mapB, mapA); | |
| return removals; | |
| } | |
| console.log(anagram('cde', 'abc')); | |
| console.log(anagram('fcrxzwscanmligyxyvym', 'jxwtrhvujlmrpdoqbisbwhmgpmeoke')); //30 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment