242. Valid Anagram – Solution [Brute-Force to Best]

Here’s the question link on Leetcode 242. Valid Anagram:

https://leetcode.com/problems/valid-anagram/description

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;
    }
};
242. Valid Anagram Brute Force Solution

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;
    }
};
242. Valid Anagram Optimal Solution

Leave a Reply