codejump
MediumPythonJavaScriptTypeScript

Hash Table — Group Anagrams

Data StructuresHash TableStrings

Group the words that are anagrams of each other (same letters, any order).

The trick is choosing a canonical key: two words are anagrams exactly when
they produce the same key, so a hash table from key → group does the rest in
one pass.

Output order (deterministic)

  • Groups appear in the order their first word appears in the input.
  • Words inside a group keep their input order.

Examples

solve(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])
  → [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

solve(['a'])   → [['a']]
solve([''])    → [['']]

Constraints

  • Words contain lowercase English letters only.
  • Sorting each word to build the key is fine; a 26-slot letter count is a

faster O(k) alternative.

Sample tests

Test #1The classic example
Input: [["eat","tea","tan","ate","nat","bat"]]
Output: [["eat","tea","ate"],["tan","nat"],["bat"]]
Test #2A single word
Input: [["a"]]
Output: [["a"]]
Test #3The empty string is its own group
Input: [[""]]
Output: [[""]]