Skip to content

Instantly share code, notes, and snippets.

@BenDMyers
Last active November 22, 2021 05:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenDMyers/2aed4fd8d68044546b74ec1f6043f304 to your computer and use it in GitHub Desktop.
Save BenDMyers/2aed4fd8d68044546b74ec1f6043f304 to your computer and use it in GitHub Desktop.
RWC: Group Anagrams
/**
* 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