Are two strings anagrams?
Sorting both and comparing is O(n log n) and fits on one line. Counting is O(n): add up the letters of the first, subtract the letters of the second, and if every count reaches zero they are anagrams. Check lengths first — it is a free rejection.
Overview
Sorting versus counting
sorted(a) == sorted(b) is correct, obvious and O(n log n). It is a perfectly good answer to give first, and then improve.
Counting is O(n). Build a frequency map of the first string, walk the second decrementing, and check nothing is left over. With a Counter that is two lines; done by hand it is a loop and a dictionary.
Both need the length check first. Different lengths cannot be anagrams, and rejecting there avoids the work entirely.
Step through it
What to watch
- The counts rise on the first string and fall on the second.
- Reaching zero and being deleted is what makes the final check a simple emptiness test.
- A length mismatch rejects before any counting starts.
Say this out loud
"Sorted comparison is the one-liner, O(n log n). Better is a Counter: add one string, subtract the other, and everything should cancel. O(n) time, O(k) space in the alphabet size."