AceYourInterviews
Checking sign-in…

4. Group Anagrams

IntermediateCanonical signatures and grouped multiplicity

Place words into the same group when they contain exactly the same letters with exactly the same counts. Every input occurrence belongs to one group, even when the same word is supplied more than once.

Keep the original relative order within each group. The examples and contract specify how groups are compared; do not discard repeated input occurrences.

Example 1

Input

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

Output

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

Explanation: Members share frequency vectors; another outer group order is equally valid.

Example 2

Input

["","a","","a"]

Output

[["",""],["a","a"]]

Explanation: Empty words and duplicate occurrences must not disappear.

Constraints

  • 0 <= words.length <= 104
  • 0 <= words[i].length <= 100
  • sum(words[i].length) <= 105
  • Words contain only lowercase English letters. Preserve occurrence order inside each group; group order is unrestricted.
Hints
Hint 1

What canonical representation identifies the same letter multiset?

Hint 2

Map that signature to a list of original occurrences.

Hint 3

Use an unambiguous 26-count key and append words in input order.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Shared signatures and duplicate occurrences

["eat","tea","tan","ate","eat"]
[["eat","tea","ate","eat"],["tan"]]