⌘K
Flycodx

Group Anagrams

Group Anagrams

MediumHash Maps57% accepted

Given a list of n words, group all words that are anagrams of each other into the same group. Two words are anagrams if they contain the same characters with the same frequencies (order does not matter). Example: 6 words "eat tea tan ate nat bat" → groups: "ate eat tea" / "bat" / "nat tan"

Input format — only if your code reads from stdin

Input format: - First line: integer n (number of words) - Second line: n space-separated lowercase words Output: each group on its own line with words sorted alphabetically within the group. Print groups in lexicographic order of their first word.

Approach

Sort each word to produce its canonical "anagram key" (e.g., "eat" → "aet"). Use a hash map from sorted-key to the list of original words. Sort each group and the final group list before printing.

Input

6 eat tea tan ate nat bat

Output

[["ate","eat","tea"],["bat"],["nat","tan"]]
  • •1 ≤ n ≤ 10^4, words contain only lowercase English letters
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3