Data Structures19 sections · 729 units
Open in Course

Group Anagrams - Key Design

Canonical form

Two approaches for the key:

1.1. Sorted string: sort the characters. "eat", "tea", "ate" all become "aet".

2.2. Character count: represent as a tuple of 26 counts. "eat" becomes (1,0,0,0,1,0,...,1,0,0). Sorted string is simpler to implement. Character count is faster for long strings (O(n)O(n) vs O(nlogn)O(n \log n)). Both create a canonical form that's identical for all anagrams.