All problems
0005MediumArrayHash TableStringSorting

Bin Label Families

Tracked in this browser only
Write code

Trains the technique from

LeetCode 49Group Anagrams

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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