Skip to content

Group anagrams

MediumPython 3ArraysHash tablesStringsSorting

You are given a list strings of lowercase strings. Group the strings so that each group contains exactly the strings that are anagrams of one another, and return the list of groups.

Two strings are anagrams if they contain the same characters with the same frequencies, possibly in a different order. Every input string must appear in exactly one output group. The order of the groups does not matter, and the order of strings within a group does not matter.

Constraints:
  - 0 <= len(strings) <= 10^4
  - 0 <= len(strings[i]) <= 100
  - strings[i] contains only lowercase English letters
Examples:
  ["eat", "tea", "tan", "ate", "nat", "bat"] ->
    [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
  [""] -> [[""]]
  ["abc"] -> [["abc"]]
  ["", "", "b"] -> [["", ""], ["b"]]

Python 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.

Loading the editor…