Practice

Group Anagrams

Module 6 · Hash Tables

Problem

Given an array of strings, group the anagrams together (any group order, any order within groups).

Examples

Example 1

Input["eat","tea","tan","ate","nat","bat"]Output[["eat","tea","ate"],["tan","nat"],["bat"]]

Example 2

Input[""]Output[[""]]

Example 3

Input["a"]Output[["a"]]

Constraints

1 ≤ count ≤ 10⁴ · 0 ≤ each length ≤ 100 · lowercase English letters.

Attempt it first

This is the Group verb, and Valid Anagram already gave you the hard part. The whole design problem is one question: what canonical key makes "same key" mean exactly "are anagrams"? There are two good answers with a real trade-off.