The “Valid Anagram” problem is a classic string question that asks whether two given strings, s
and t
, are anagrams of each other.
Two strings are considered anagrams if they contain the exact same characters with the exact same frequencies, though possibly in a different order.
For example:
s = "anagram"
, t = "nagaram"
→ Output: true
s = "rat"
, t = "car"
→ Output: false
Validating anagrams appears in problems involving string normalization, word frequency comparison, and even in applications like plagiarism detection or cryptography. It reinforces core concepts in character counting and hash-based comparison.
The most intuitive solution is to count the frequency of characters in both strings and compare the results.
This is easily done using a Counter
(or a hash map) for each string.
s
and t
differ, return false
immediately.s
and t
.true
; otherwise, return false
.
Input: s = "listen"
, t = "silent"
s
: {l:1, i:1, s:1, t:1, e:1, n:1}
t
: {s:1, i:1, l:1, e:1, n:1, t:1}
true
An equally valid solution is to sort both strings and compare the results. If the sorted versions of s
and t
match, then they must be anagrams.
s = "anagram"
→ sorted(s) = "aaagmnr"
t = "nagaram"
→ sorted(t) = "aaagmnr"
true
Time Complexity: O(n log n), due to sorting.
Using Counters:
Time Complexity: O(n), where n is the length of the strings.
Space Complexity: O(1), because we use at most 26 letters (if constrained to lowercase English).
Using Sorting:
Time Complexity: O(n log n)
Space Complexity: O(n) due to the creation of sorted copies.
false
true
(two empty strings are trivially anagrams)"a"
and "A"
are not the sameThe “Valid Anagram” problem is simple but powerful. It demonstrates how to solve problems by counting frequency or sorting structures. Mastering both approaches sharpens your skills in working with strings and hash maps—critical tools in programming and algorithm design.