Last active
May 18, 2020 04:55
-
-
Save muhsalaa/b78453b51076e28b93b43343565238e8 to your computer and use it in GitHub Desktop.
Interview question about group anagram answer in javascript
This file contains 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
// input: ['tea','you', 'eat', 'ate', 'ouy', 'hard'] | |
// output: [ | |
// ['tea', 'eat', 'ate'], | |
// ['you', 'ouy'], | |
// ['hard'] | |
// ] | |
function groupAnagram(arr) { | |
// we will put result here | |
const output = {}; | |
// normalize word to get the similarity among all word | |
const normalizeWord = (word) => word.split('').sort().join(''); | |
// iterate the array input | |
arr.forEach((x) => { | |
// if key exist in output | |
output[normalizedWord(x)] | |
// push the value | |
? output[normalizedWord(x)].push(x) | |
// else give a new key and value to output | |
: (output[normalizedWord(x)] = [x]); | |
}); | |
// finally, get all output values with Object.values() method | |
console.log(Object.values(output)); | |
} | |
// ref: https://medium.com/javascript-in-plain-english/algorithms-101-group-anagrams-in-javascript-b3e3c10d211e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment