Print Anagrams Together | Practice
You're given an array of strings. Cluster them so that any two words built from the same letters (same letter counts, regardless of order) land in the same group — that's what makes them anagrams of each other. Groups can come back in any order, and so can the words inside each group.
Two empty strings count as anagrams of each other too.
Input Format
Implement groupAnagrams(words). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
The order of the outer result array does not matter. Order inside each group does not matter either.
Sample Input and Output
Example 1 · Run Sample
Input
words = ["eat","tea","tan","ate","nat","bat"] Output
[["bat"],["nat","tan"],["ate","eat","tea"]] Example 2
Input
words = [""] Output
[[""]] Constraints
- 1 <= words.length <= 100
- 0 <= words[i].length <= 10
- Words contain lowercase English letters.
Test Cases (2)
Case 1
Args: [["eat","tea","tan","ate","nat","bat"]]
Expected: [["bat"],["nat","tan"],["ate","eat","tea"]]
Case 2
Args: [[""]]
Expected: [[""]]
Topics
Hash Map with Sorted Key
function groupAnagrams(words) {
const map = new Map();
for (const w of words) {
const key = w.split('').sort().join('');
if (!map.has(key)) map.set(key, []);
map.get(key).push(w);
}
return [...map.values()];
}Time: O(n × k log k) | Space: O(n × k)
Saved in this browser only. Private to you.