KatInterview

Group Words by Character Frequency

StringsAuto-graded · 21 test cases
MediumAuto-gradedStringshash-mapsortingstring-manipulation

Last updated

Tests hash map construction with canonical keys to partition strings by anagram equivalence

You are given an array of strings. Your task is to partition these strings into groups where each group contains words that are anagrams of one another. Two words are anagrams if they contain exactly the same characters with identical frequencies, regardless of order.

Return the groups as a list of lists. The order of groups in the output and the order of words within each group should match the order in which they first appear in the input.

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • Each string contains only lowercase English letters
  • Total length of all strings combined does not exceed 10^5

Examples

Example 1

Input: group_anagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])

Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

Example 2

Input: group_anagrams([''])

Output: [['']]

Example 3

Input: group_anagrams(['a'])

Output: [['a']]

Hints

Hint 1

Two words are anagrams if and only if sorting their characters produces identical sequences. Can you use this as a grouping key?

Hint 2

A hash map lets you collect all words that share the same canonical form into the same bucket in a single pass

Hint 3

Remember that lists aren't hashable in Python—convert your sorted character sequence to a tuple or joined string before using it as a dictionary key