Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Approach 1
  • Two unordered count map and a final loop to check if counts are same in both
  • Time: O(n) Space: O(n)
class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size()) {
            return false;
        }
 
        unordered_map<char,int> countS;
        unordered_map<char,int> countT;
 
        for(int i = 0; i < s.size(); i++) {
            countS[s[i]]++;
            countT[t[i]]++;
        }
 
        for(const auto& pair: countS) {
            if(countS[pair.first] != countT[pair.first]) {
                return false;
            }
        }
        return true;
    }
};
Approach 2
  • Create an integer array of size 26
  • Loop through string and add 1 to array if it is in first string and -1 for second
  • Loop through the array and if it is not zero for any key then it is not anagram
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()) {
            return false;
        }
 
        int[] help = new int[26];
 
        for(int i = 0; i < s.length(); i++) {
            help[s.charAt(i) - 'a']++;
            help[t.charAt(i) - 'a']--;
        }
 
        for(int n: help) {
            if(n != 0) {
                return false;
            }
        }
        return true;
    }
}
  • The number 256 represents the total number of possible character codes in the **Extended ASCII character set**.
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()) {
            return false;
        }
        int[] count = new int[256];
        for(int i = 0; i < s.length(); i++) {
            count[s.charAt(i)]++;
            count[t.charAt(i)]--;
        }
 
        for(int n: count) {
            if(n != 0) {
                return false;
            }
        }
 
        return true;
    }
}