Group Anagrams
Real-world version: Bin Label FamiliesThe statement here is our own: the same inputs, outputs and technique.
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.
def group_by_letters(labels: list[str]) -> list[list[str]]:public List<List<String>> groupByLetters(String[] labels)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Sort the PeopleReal-world version: Season Leaderboard From Two Parallel ListsEasy
- Find Resultant Array After Removing AnagramsReal-world version: Clearing Rearranged Labels Off the ShelfEasy
- Accounts MergeReal-world version: Merge Crew Badge RecordsMedium
- Top K Frequent WordsReal-world version: Most Drawn Part CodesMedium