Ads Top

Interview Practice: Javascript Group Anagrams Solution

Anagram : a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.

Previously, I posted a solution for finding a single anagram within a word, you can see that solutiuon here

A step up from solving for a single anagram is to group anagrams together. For example, given the following input, this function should presetnt the output give below :

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

The solution for this problem is a combination of two other problems. A combination of the TwoSum problem and the basic anagram finder problem can get you to a solution for the group anagram problem.

Key mehtods for solving this problem
a hash for storing and tracking words (Js object)
split, sort, join method used in original anagram problem

Here is the code to implement this solution:
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' ] ]



Leetcode Group Anagram

Leave a Comment

No comments:

Powered by Blogger.