Jumble Puzzle Bins

Mediumhash mapAlso known as Group Anagrams

You set the weekly word jumble for a local paper. The best puzzles are sets of words built from exactly the same letters, like least, slate and stale: readers get the scrambled letters and must find every word.

Readers mail in word suggestions, and you have a long list of them. You want to sort them into bins, one bin per set of letters, so you can see at a glance 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 the letters a, e, l, s, t. tea, eat and ate share a, e, t. bus matches nothing and gets a bin of its own. The bins come in the order of their first words: least, then tea, then bus.
Example 2
Input
words = ["ton", "not", "onto"]
Output
[["ton", "not"], ["onto"]]
Whyonto uses the same three kinds of letter as ton, but it has two o's and four letters, so it is not a rearrangement. It goes in 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

For each word, compare it with the first word of every bin so far, using a letter-count check like the one in Same Letter Tiles. Put it in the first bin that matches, or start a new bin.

If most words are different, each word is compared with almost every bin, so this costs about n² comparisons. With 10,000 words that is around 50 million word comparisons, 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