Here’s the question link on Leetcode 242. Valid Anagram:
https://leetcode.com/problems/valid-anagram/description
Contents
Brute Force – Sorting
The simplest approach is to sort both strings.
If both strings are anagrams, sorting them will put their characters in exactly the same order. So, we just compare the sorted strings.
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
Optimal – Frequency Counting
Instead of sorting, we can simply count how many times each character appears.
Since the problem guarantees lowercase English letters, we only need an array of size 26.
We’ll increment the count for every character in s and decrement it for every character in t.
If both strings are anagrams, all counts will eventually become zero.
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) return false;
vector<int> freq(26, 0);
for(int i = 0; i < s.size(); i++) {
freq[s[i] - 'a']++;
freq[t[i] - 'a']--;
}
for(int count : freq) {
if(count != 0) return false;
}
return true;
}
};