
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:
Leetcode Group Anagram
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:
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
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
No comments: