Overview
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An anagram is a word formed by rearranging the letters of another word, using all the original letters exactly once.
Constraints
1 <= strs.length <= 10,0000 <= strs[i].length <= 100strs[i]consists of lowercase English letters.- Each group should be sorted alphabetically, and the groups themselves sorted by the first element.
Examples
groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]); // => [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
groupAnagrams([""]); // => [[""]] groupAnagrams(["a"]); // => [["a"]]
Solution
Reveal solution
function groupAnagrams(strs) {
const map = new Map();
for (const s of strs) {
const key = s.split("").sort().join("");
if (!map.has(key)) map.set(key, []);
map.get(key).push(s);
}
const groups = [...map.values()];
groups.forEach(g => g.sort());
groups.sort((a, b) => a[0].localeCompare(b[0]));
return groups;
}Sort each string to create a canonical key. Group by that key using a hash map. O(n * k log k) where k is the max string length.
Resources
string-anagram-groups.js
String Anagram Groups
mediumcodingAlgorithmsHash Map
Overview
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An anagram is a word formed by rearranging the letters of another word, using all the original letters exactly once.
Constraints
1 <= strs.length <= 10,0000 <= strs[i].length <= 100strs[i]consists of lowercase English letters.- Each group should be sorted alphabetically, and the groups themselves sorted by the first element.
Examples
groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]); // => [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
groupAnagrams([""]); // => [[""]] groupAnagrams(["a"]); // => [["a"]]
Solution
Reveal solution
function groupAnagrams(strs) {
const map = new Map();
for (const s of strs) {
const key = s.split("").sort().join("");
if (!map.has(key)) map.set(key, []);
map.get(key).push(s);
}
const groups = [...map.values()];
groups.forEach(g => g.sort());
groups.sort((a, b) => a[0].localeCompare(b[0]));
return groups;
}Sort each string to create a canonical key. Group by that key using a hash map. O(n * k log k) where k is the max string length.
Resources
NameTopicDifficulty
103 of 103 problems