Group Anagrams using Javascript
Given an array of strings strs, group the anagrams together.
Anagram: An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
For example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Note: All inputs will be in lower-case.
Using hashmap
To solve this we will use Hash Table , where each key is sorted string and each value is the list of strings from the initial input that when sorted, are equal to key.
Time Complexity Analysis
Time Complexity: O(NKlog(K))
, where N is the length of strs, and K is the maximum length of a string in strs.
The outer loop has complexity O(N)
as we iterate through each string.
Then, we sort each string in O(KlogK)
time.
Space Complexity: O(N*K), the total information content stored in ans
Solution using Javascript:
const groupAnagrams = function (strs) {
const hash = {};
for (let i = 0; i < strs.length; i += 1) {
const str = strs[i];
const key = sortStr(str);
console.log(key);
hash[key] = hash[key] || [];
hash[key].push(str);
}
let result = [];
for (const i in hash) {
result.push(hash[i]);
}
return result;
};
const sortStr = (str) => {
const arr = str.split('');
arr.sort((a,b) => a > b ? 1 : -1);
return arr.join('');
}