Skip to content

Instantly share code, notes, and snippets.

@jslnriot
Last active December 19, 2022 16:53
Show Gist options
  • Save jslnriot/5dd1d663fa1749febecdf2b356d40dd8 to your computer and use it in GitHub Desktop.
Save jslnriot/5dd1d663fa1749febecdf2b356d40dd8 to your computer and use it in GitHub Desktop.
function groupAnagrams(strs) {
// create a hash map to store the words and their sorted versions as the keys
let hash = {};
// loop over the words
for (let word of strs) {
let cleansed = word.split("").sort().join("");
// check if the sorted word is already in the map
if (hash[cleansed]) {
// if it is, add the word to the list of anagrams for that key
hash[cleansed].push(word);
} else {
// if it is not, create a new entry in the map with the sorted word as the key and the word as the value
hash[cleansed] = [word];
}
}
return Object.values(hash);
}
// Run the function with inputStrings
const inputStrings = ["eat","tea","tan","ate","nat","bat"]
const result = groupAnagrams(inputStrings)
console.log(result)
// Result - [ [ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment