There is no string in strs that can be rearranged to form "bat".
The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.
Example 2:
Input:strs = [""]
Output:[[""]]
Example 3:
Input:strs = ["a"]
Output:[["a"]]
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.
Solutions
Solution 1: Hash Table
Thinking
The first idea is pairwise anagram checks: sort each string and compare. Correct, but \(n \le 10^4\) and \(k \le 100\) make \(O(n^2 \cdot k \log k)\) too slow.
Pairwise comparison is the bottleneck. Anagrams share one sorted form — that string is the group id.
Use the sorted string as key and a list of originals as value. One pass into a hash table clusters them; no pairwise matching.
Traverse the string array, sort each string in character dictionary order to get a new string.
Use the new string as key and [str] as value, and store them in the hash table (HashMap<String, List<String>>).
When encountering the same key during subsequent traversal, add it to the corresponding value.
Take strs = ["eat", "tea", "tan", "ate", "nat", "bat"] as an example. At the end of the traversal, the state of the hash table is:
key
value
"aet"
["eat", "tea", "ate"]
"ant"
["tan", "nat"]
"abt"
["bat"]
Finally, return the value list of the hash table.
The time complexity is \(O(n\times k\times \log k)\), where \(n\) and \(k\) are the lengths of the string array and the maximum length of the string, respectively.
Solution 1 sorts every string, \(O(k \log k)\) each. The alphabet is \(26\) lowercase letters; with \(k \le 100\) the \(\log k\) factor is waste.
What it lacks is a cheaper key. Count each letter and use the length-\(26\) tuple as the key. Same hash grouping, linear per string.
We can also change the sorting part in Solution 1 to counting, that is, use the characters in each string \(s\) and their occurrence times as key, and use the string \(s\) as value to store in the hash table.
The time complexity is \(O(n\times (k + C))\), where \(n\) and \(k\) are the lengths of the string array and the maximum length of the string, respectively, and \(C\) is the size of the character set. In this problem, \(C = 26\).