Group Anagrams

Hard ⏱ 18 min 29% acceptance ★★★★★ 4.7
Write a function group_anagrams(words) that groups words that are anagrams of each other into lists, using a dict keyed by each word's sorted-letters signature. Return the groups as a list of lists; each group is in first-seen order, and groups appear in the order their signature was first encountered.

Examples

Example 1
Input
group_anagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])
Output
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Explanation

'eat','tea','ate' share sorted signature 'aet'; 'tan','nat' share 'ant'; 'bat' is alone.

Constraints

  • Preserve first-seen order both within and across groups.

Topics

Dictionariesgroupingstrings

Companies

MicrosoftAdobeApple

Hints

Hint 1

Key each word by `''.join(sorted(word))`.

Hint 2

Use `groups.setdefault(signature, []).append(word)`, then return `list(groups.values())`.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.