Jumble Puzzle Bins

Mediumhash mapAlso known as Group Anagrams

You set the weekly word jumble for a local paper. The best puzzles are words built from exactly the same letters, like least, slate and stale. Readers mail in a long list of suggestions, and you want to sort them into bins, one per set of letters, to see which bins are big enough for a puzzle.

Your task

Write groupJumbles(words). Put two words in the same bin exactly when one is a rearrangement of the other: the same letters, each used the same number of times. Return the list of bins.

Order matters, so the answer is unique. Bins appear in the order their first word appears in words. Inside a bin, words keep their order from words. If a word is suggested twice, both copies go in its bin. An empty list gives [].

groupJumbles(words: string[]) → string[][]

Examples

Example 1
Input
words = ["least", "tea", "slate", "eat", "bus", "stale", "ate"]
Output
[["least", "slate", "stale"], ["tea", "eat", "ate"], ["bus"]]
Whyleast, slate and stale share a, e, l, s, t; tea, eat and ate share a, e, t; bus gets its own bin. Bins follow the order of their first words: least, tea, bus.
Example 2
Input
words = ["ton", "not", "onto"]
Output
[["ton", "not"], ["onto"]]
Whyonto uses the same kinds of letter as ton, but has two o's, so it is not a rearrangement and gets its own bin.

Constraints

  • 0 ≤ words.length ≤ 10,000
  • 0 ≤ words[i].length ≤ 20
  • Words contain only lowercase letters a to z.
Start with brute force

Compare each word with the first word of every bin so far, using a letter-count check like the one in Same Letter Tiles, and join the first match or start a new bin. If most words differ, that is about n² comparisons: around 50 million for 10,000 words, each reading up to 20 letters.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code