Last active
November 22, 2021 05:37
-
-
Save BenDMyers/2aed4fd8d68044546b74ec1f6043f304 to your computer and use it in GitHub Desktop.
RWC: Group Anagrams
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
/** | |
* Take an array of phrases and return a list of anagram groups | |
* @param {string[]} phrases list of strings which may or may not be anagrams of other strings in the same list | |
* @returns {string[][]} a list of arrays of strings, where every string in an inner array is an anagram of the others | |
*/ | |
function groupAnagrams(phrases) { | |
/** @type {Object<string, string[]>} */ | |
const anagramGroups = {}; | |
// Create a map of anagram groups | |
for (const phrase of phrases) { | |
const sortedLetters = phrase | |
.toLowerCase() // Capitalization doesn't matter for anagrams | |
.replace(/[^a-z]/g, '') // Remove any character that isn't a letter | |
.split('') // Convert to an array of letters | |
.sort() // Arrange those letters alphabetically | |
.join(''); // Make it a string again | |
if (anagramGroups[sortedLetters]) { | |
anagramGroups[sortedLetters].push(phrase); | |
} else { | |
anagramGroups[sortedLetters] = [phrase]; | |
} | |
} | |
return [...Object.values(anagramGroups)]; | |
} | |
const groups = groupAnagrams(['eat', 'tea', 'ten', 'poop', 'net', 'ate']); | |
console.log(groups); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment