Given an array of strings strs, group the anagrams together. You can return the answer in any order.
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.
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
var groupAnagrams = function (strs) {
if (!strs || !strs.length) {
return null;
}
let anagrams = {};
for (let x = 0; x < strs.length; x++) {
const sortedWord = strs[x].split('').sort().join();
if (sortedWord in anagrams) {
anagrams[sortedWord].push(strs[x])
} else {
anagrams[sortedWord] = [strs[x]];
}
}
return Object.values(anagrams);
}
Time Complexity : O(w*n*log(n))
Space Complexity : O(wn)
Top comments (2)
Using the upcoming
Array.groupBy
(already available in Firefox Nightly):@jonrandy thanks