You get a list of lowercase words, strs. Two words are anagrams when one can be turned into the other by reordering its letters, using every letter exactly once.
Put the words into groups so that each group holds words that are anagrams of each other, and every word lands in exactly one group. Return the groups. Neither the groups nor the words inside a group need to be in any particular order.
Example 1
Input: strs = ["rat", "tar", "god", "art", "dog"] Output: [["rat", "tar", "art"], ["god", "dog"]] Why: rat, tar and art reorder the same three letters
2 more examples and the constraints
Example 2
Input: strs = ["", "", "z"] Output: [["", ""], ["z"]] Why: two empty words are anagrams of each other
Example 3
Input: strs = ["ab", "cd"] Output: [["ab"], ["cd"]] Why: no letters in common, so two groups of one
Constraints
- 1 ≤ number of words ≤ 10,000
- 0 ≤ length of each word ≤ 100
- Words use only the letters a to z
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Compare with every groupO(n²·k log k)
- Sorted word as keyO(n·k log k)
- Letter counts as keyO(n·k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 words of 100 letters | Verdict |
|---|---|---|---|
| Compare with every group | O(n²·k log k) | Mention it, then move on | |
| Sorted word as key | O(n·k log k) | Passes; the usual answer | |
| Letter counts as key | O(n·k) | Best; no sorting at all |
n = number of words, k = length of the longest word.
Edge cases to test
- Empty words. "" is a word with no letters; two of them form one group, ["", ""].
- The same word twice. ["aa", "aa"] is one group that keeps both copies.
- Same letters, different amounts. "aab" and "abb" share letters but are not anagrams; counts tell them apart.
- A single word. ["q"] gives [["q"]]: one group of one.
Common mistakes
- Using a set of letters as the key, so "aab" and "abb" land in the same group.
- Building the count key by gluing numbers together with no separator, so different counts make the same string.
- Using a list as a dictionary key in Python; it must be a tuple or a string.
How to talk through it
- 1Clarify. Only lowercase letters? Can a word be empty? Does the order of groups or of words inside a group matter?
- 2Give the brute force. Compare each word against each group; say why that is O(n²) comparisons.
- 3Find the fingerprint. Anagrams look the same once order is ignored: sorted letters or letter counts. That fingerprint is a hash key.
- 4Code the count key. Count 26 letters per word, turn them into a tuple or joined string, and append the word to its list.
- 5Test out loud. Run the empty-word, repeated-word and aab versus abb cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?