Sorting builds the fastest key for words, counting for long strings
Building a key costs time. Here are two keys that are equal exactly for anagrams of lowercase words. A third, count_key, counts how many a's, b's and so on up to z's a word has, and you'll write it below:
from collections import Counter
def sorted_key(word):
return "".join(sorted(word))
def counter_key(word):
return tuple(sorted(Counter(word).items()))
Timed on a random lowercase string of length k:
| k | sorted_key | count_key | counter_key |
|---|---|---|---|
| 8 | 0.29 µs | 0.47 µs | 1.03 µs |
| 1,000,000 | 91.4 ms | 46.9 ms | 23.6 ms |
Sorting is O(k log k), and the counting keys are O(k). Yet at word length, sorting is fastest. It runs in C, while count_key loops in Python and Counter has more setup.
On a million characters the counting keys win. Counter, which counts in C, is nearly four times faster than sorting.
So for n words of length k, grouping by sorted letters costs O(n k log k). Sorting and comparing every pair costs O(n² k log k).
Hashing a string is O(k) too, but Python caches a string's hash. The first hash() of a 100,000,000-character string took 35.0 ms, and the second 0.54 µs.
In the editor, finish count_key(word), the counting key from the timings. Add 1 to counts[ord(ch) - ord('a')] for each letter, and return the counts as a tuple, so that the key is hashable.