v9.1.1
Menu

Group Anagrams

mediumPRODesign & Hash MapsUber DSA

Given an array of strings, group the anagrams together.

Return a list of groups, where each group is a list of the input strings that are anagrams of each other. Groups and the words inside them may be in any order.

For display, groups are printed one per line, words space-separated and sorted, groups sorted by first word.

Example

Input
eat,tea,tan,ate,nat,bat
Output
ate eat tea
bat
nat tan
Reasoning
  • Input: six lowercase words, eat,tea,tan,ate,nat,bat. Two words are anagrams exactly when they use the same letters the same number of times; the order of letters is irrelevant.
  • Count the letters of each word. eat, tea and ate all contain one aa, one ee and one tt, so they form one group. tan and nat each contain one aa, one nn and one tt, a second group. bat has one aa, one bb, one tt, a combination no other word shares, so it stands alone.
  • Every word lands in exactly one group, and the group sizes 3+2+1=63 + 2 + 1 = 6 add up to the input length.
  • Output: each group's words are shown in alphabetical order and the groups are ordered by their first word, giving three lines:
    ate eat tea
    bat
    nat tan
  • Notice that bat and tan share two letters but still land in different groups: one differing letter is enough to separate them. A word of length 0 would form its own group too.

Constraints

  • 1 <= len(strs) <= 10^4
  • 0 <= len(strs[i]) <= 100
  • strs[i] is lowercase English letters

Learn this in

More from Uber DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.