Show problems as
Classic problem #49MediumArrayHash TableStringSorting

Group Anagrams

Real-world version: Bin Label Families
Tracked in this browser only
Read Group Anagrams on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstHashmaps · Strings, animated step by step

A warehouse stamps each storage bin with a short code made of lowercase letters. Two codes belong to the same family when one can be produced by shuffling the letters of the other, which happens exactly when both codes use every letter the same number of times. A code with a letter repeated more often than in another code is therefore in a different family.

Given the array labels, split every code into its family. Each code lands in exactly one family, and repeated codes stay together in the same family, once per occurrence.

Return the families as a list of lists. The families may come back in whatever sequence you like, and the codes inside a family may be arranged however you like.

Examples

Example 1

Input
labels = ["bat", "tab", "cage", "abt", "gaec", "dog"]
Output
[["abt", "bat", "tab"], ["cage", "gaec"], ["dog"]]

`bat`, `tab` and `abt` all use one `a`, one `b` and one `t`, so they share a family; `cage` and `gaec` share another; `dog` has no partner and forms a family alone.

Example 2

Input
labels = ["listen", "silent", "enlist", "tinsel"]
Output
[["enlist", "listen", "silent", "tinsel"]]

Every code draws on the same six letters once each, so a single family holds all four.

Example 3

Input
labels = ["aab", "abb", "aba"]
Output
[["aab", "aba"], ["abb"]]

`aab` and `aba` both carry two `a` and one `b`, while `abb` carries one `a` and two `b`, so counts, not just the set of letters, decide the split.

Constraints

  • 1 <= labels.length <= 10^4
  • 0 <= labels[i].length <= 100
  • labels[i] consists of lowercase English letters.

The groups you return, and the values inside each group, may be in any order.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def group_by_letters(labels: list[str]) -> list[list[str]]:
Java
public List<List<String>> groupByLetters(String[] labels)