Given two strings, return whether one is an anagram of the other: the same letters with the same counts, in any order. The strings contain lowercase English letters.
Before you code
Sorting both strings and comparing works in O(n log n). Two strings are anagrams exactly when their letter counts match, and counting is the first pass of counting sort: O(n) with 26 counters.
Hints
- If the lengths differ, return false immediately.
- Use an array of 26 counts: add 1 for each letter of
sand subtract 1 for each letter oft. - The strings are anagrams if every count ends at 0.
- Follow-up: for arbitrary Unicode text, use a hash map of counts instead of a fixed array.
Production & complexity notes
When solving Valid anagram on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Counting and radix sort to reinforce the underlying pattern.
What it practices
Using the values themselves instead of comparisons, from Counting and radix sort.