We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Using JavaScript, the solutions you can find online will time out with the larger test-cases, which made this problem more difficult than you would think. I had to change the approach completely and you won't find this solution online. I'm not going to share my code, but it processes VERY quickly with standard JavaScript Array functions. Here is the path...
Build a function which sorts your data:
1- Use both input strings and break each character into a startingArray.
2- Sort the array alphabetically.
3- Iterate through each array element to create a newArrays which will have all 26 letters consolidated into the same newArray index (so that newArray[0] will contain all the "a" elements, newArray[1] will contain all "b" elements, etc.). Trick: each newArray will have 26 indexes, even if some are empty (but must be defined).
4- Use this function for both input lines.
Build another function to take both of the newArrays and calculate the differences between each of their elements (number of b's in one array versus the number of b's in the other). The total differences at each index will ultimately provide your answer.
I hope this helps the JavaScript coders!
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Making Anagrams
You are viewing a single comment's thread. Return to all comments →
Using JavaScript, the solutions you can find online will time out with the larger test-cases, which made this problem more difficult than you would think. I had to change the approach completely and you won't find this solution online. I'm not going to share my code, but it processes VERY quickly with standard JavaScript Array functions. Here is the path...
Build a function which sorts your data: 1- Use both input strings and break each character into a startingArray. 2- Sort the array alphabetically. 3- Iterate through each array element to create a newArrays which will have all 26 letters consolidated into the same newArray index (so that newArray[0] will contain all the "a" elements, newArray[1] will contain all "b" elements, etc.). Trick: each newArray will have 26 indexes, even if some are empty (but must be defined). 4- Use this function for both input lines.
Build another function to take both of the newArrays and calculate the differences between each of their elements (number of b's in one array versus the number of b's in the other). The total differences at each index will ultimately provide your answer.
I hope this helps the JavaScript coders!