Problem Description#
Given an array of strings, group the anagrams
together. You can return the results in any order.
Anagrams are new words formed by rearranging all the letters of the source word.
Example 1:
Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
1 <= strs.length <= 10^4
0 <= strs[i].length <= 100
strs[i] only contains lowercase letters
Approach#
- Strings that are anagrams of each other must contain the same letters, just in a different order.
- We can define a map structure to place anagram strings under the same key.
- This key can be the sorted string or the sum of the charcode values of the string, or a string that counts the number of characters.
Solution#
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
if (strs.length === 1) return [strs];
const m = new Map();
for (let i = 0; i < strs.length; i++) {
const temp = strs[i].split('').sort().join('');
// or const temp = Array.from(strs[i]).reduce((acc, curr) => acc + curr.charCodeAt(), 0);
if (m.has(temp)) {
m.set(temp, [...m.get(temp), strs[i]]);
} else {
m.set(temp, [strs[i]]);
}
}
return Array.from(m.values());
};