Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

Group the words that are anagrams

Medium · Target 20 minutes · Arrays and hashing· Type asked at

You're given an array words of lowercase strings (some may be empty). I'd like you to put the words into groups so that two words are in the same group exactly when one is an anagram of the other, which means they use the same letters the same number of times.

So that there's only one right answer, return each group as the list of its indices in increasing order, and list the groups in the order of their first index.

Examples

InputOutputWhy
words = ["eat", "tea", "tan", "ate", "nat", "bat"][[0, 1, 3], [2, 4], [5]]The eat, tea and ate group starts at index 0, then tan and nat start at 2, and bat is on its own.
words = [""][[0]]The empty word is still a word and it gets a group of its own.
words = ["ab", "ba", "ab"][[0, 1, 2]]A word repeated is an anagram of itself, so all three go in one group.

Constraints

  • 1 ≤ n ≤ 10⁴
  • 0 ≤ words[i].length ≤ 100
  • words[i] holds lowercase English letters only

Hints

Hint 1

Comparing every pair of words does work but it costs you O(n²) comparisons, and what you'd really like is a way for each word to find the group it belongs to straight away.

Hint 2

I'd think about what the words in one group all have in common with each other and how you might write that down as a single value that a hash map could use as its key.

Hint 3

Sorting the letters of a word gives you exactly such a key and so does the list of its 26 letter counts, and either of them can go into a hash map that sends each key to its group.

Where people lose marks

  • I've seen people use an array of 26 counts as the key in a language that hashes arrays by identity, which is what JavaScript does with objects and Java does with int[], and then every word ends up in a group of its own. You'll want to turn the counts into a string before you use them as a key.
  • If you build the counts key by gluing the numbers together with nothing between them then a count of 1 followed by 11 and a count of 11 followed by 1 both come out as 111, and you'll put two words in the same group when they aren't anagrams at all.
  • It's easy to forget about the empty string, but its sorted key is just the empty string and it should get a group of its own like any other word you're given.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.