3.Valid Anagram

An Anagram is a word or phrase that's formed by rearranging the letters of another word or phrase.

All Anagrams are same when they are sorted.

Input: s = "anagram", t = "nagaram"
Output: true

Input: s = "rat", t = "car"
Output: false

Solution:-

class Solution {
public:
    bool isAnagram(string s, string t) {
        
        if(s == " " && t==" "){return true;}
        if(s==" " || t==" ") {return false;}
       
        
      vector<int> v1(26);
      vector<int> v2(26);
       bool res = true;
      for(int i=0;i<s.length();i++){
          v1[s[i]-97]++;
      }
        
      for(int i=0;i<t.length();i++){
          v2[t[i]-97]++;
      }
        
    
        for(int i=0;i<25;i++){
            if(v1[i]!=v2[i]){
                res = false;
                break;
            }
        }
        
        return res;
    }
};

Time Complexity:- O(n+m) [n is the length of 1st string] and [m is the length of 2nd string.]

Space Complexity:- O(1) Can be considered as constant as the size of the array is 26.

Last updated