Search~12 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-242hashing
A search engine corrects scrambled typing. When a user types a term, the engine checks whether it is a rearrangement of a known term. That means the same letters, in any order, each used the same number of times.
The known terms and the typed terms are made of the lowercase letters a to z. A term can be very long, up to 1,000,000 letters, for example in a technical dictionary of long identifiers.
Write are_anagrams(first, second).
first and second use only the lowercase letters a to z.true when second can be made by rearranging the letters of first: every letter occurs the same number of times in both words.false. Words of different lengths are never anagrams.Input: first = "parsley", second = "players"
Output: trueBoth words use p, a, r, s, l, e and y once each, in a different order.
Count the first word up and the second word down. The table shows how many letters have a count that is not 0.
| Step | Letter | Action | Letters with a count not 0 |
|---|---|---|---|
| 1 to 7 | p, a, r, s, l, e, y | first word: add one for each | 7 |
| 8 | p | second word: take one away | 6 |
| 9 | l | take one away | 5 |
| 10 | a | take one away | 4 |
| 11 | y | take one away | 3 |
| 12 | e | take one away | 2 |
| 13 | r | take one away | 1 |
| 14 | s | take one away | 0 |
Every count is 0, so the words are anagrams.
Input: first = "tea", second = "tee"
Output: falseThe second word has two e letters and no a.
Input: first = "ab", second = "a"
Output: falseThe lengths differ.
1 ≤ first.length ≤ 1,000,000 and 1 ≤ second.length ≤ 1,000,000 (letters)a to zCounting each letter by scanning both words costs 2 × n × n steps, which is 2 × 10^12 at n = 10^6. One pass over each word costs about 2 × n steps. The alphabet has only 26 letters, so the counts fit a small array.