DEV Community

Ruparani777
Ruparani777

Posted on

VALID ANAGRAM LEETCODE SOLUTION C++ WITH OPTIMISED SOLUTION

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.

Example 1:

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

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

Constraints:

1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters.

SOLUTION C++ :TC (OLOGN)

class Solution {
public:
    bool isAnagram(string s, string t) {
       int n1=s.length();
       int n2=t.length();
       if(n1!=n2) return false;
       sort(s.begin(),s.end());
       sort(t.begin(),t.end());

           if(s!=t)
               return false;

           return true;

    }
};
Enter fullscreen mode Exit fullscreen mode

SOLUTION C++:TC O(N)

class Solution {
public:
    bool isAnagram(string s, string t) {
  //      Time Complexity : O(N)
/* Space Complexity : O(1), Constant space. As we are using26size-frequency array to store the frequency of every character which is constant.*/
        if(s.length()!=t.length()){
            return false;
        }
        int arr[26]={0};

        for(int i=0;i<s.length();i++){  //solved using string and hashtable
            arr[s[i]-'a']++;
            arr[t[i]-'a']--;
        }
        for(int i=0;i<26;i++){
            if(arr[i]!=0){
                return false;
            }
        }
        return true;

    }

};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)