Skip to content

visual walkthrough

Valid Anagram

EasyFrequency CountReported at: AmazonMetaMicrosoft+5

Counting characters with a fixed-size array is the base of every anagram and permutation problem.

Solve on LeetCode

The idea

Two words are anagrams when they use exactly the same letters the same number of times. Sorting makes that obvious; counting gets there without sorting at all.

With counting, add one for each letter of the first word and take one away for each letter of the second. If everything cancels, they match.

Complexity

approachtimespace
Sort bothO(n log n)O(n)
Count lettersO(n)O(1)

More walkthroughs