Skip to problem
←

Group Anagrams

Medium 0 attempts

Given an array of lowercase strings words, group all anagrams together and return the groups.

Two strings are anagrams when they contain exactly the same characters with the same counts, regardless of order. For example, "aab" and "aba" are anagrams, but "abb" belongs to a different group.

Include every input entry exactly once. Repeated identical words remain repeated entries in their group; do not deduplicate them. Empty strings are anagrams of one another. Use one group per distinct anagram class, and keep words with no anagram partners in singleton groups.

Both group order and the order of words within a group may vary. Return the grouped arrays rather than printing them.

Function contract

Implement groupAnagrams(words).

Output: Return one group for each anagram class, preserving every input occurrence. Group order and word order inside each group do not matter.

Example 1

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.

Hash Map with a Sorted Character Key

Sort the characters of each word to form its key. Two words have the same key exactly when every character has the same count, so the key identifies their anagram class.

Append the original word to the array stored for that key. Always append, even if the identical word was already seen: duplicate input entries must remain in the output. Empty strings share the empty key. Finally return the map's group arrays.

Sorting a temporary character array leaves both the original words and their input order untouched.

javascript
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 × (1 + k log(k + 1))), where n is the number of words and k their maximum length. The additive term accounts for empty strings.

Space: O(n × (k + 1)) as an upper bound for stored keys, group references, and temporary character arrays.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript