Strings - Valid Anagram

Strings - Valid Anagram

Valid Anagram

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

My approach:

  1. I used the concept of hashing.

  2. You can use hashmap or in this case just a simple array of size 26.

  3. Iterate through 's' string and update hash array by increasing the value of alphabets.

  4. Iterate through 't' string and update hash array by decreasing the value of alphabets.

  5. Iterate through hash array and,

    • if (arr[i]!=0) -> return false

    • else -> return true

Code:

// TIME COMPLEXITY : O(N)+O(N)
// SPACE COMPLEXITY : O(1)

class Solution {
public:
    bool isAnagram(string s, string t) {

        vector<int> arr(26,0);

        for(int i=0;i<s.size();i++){
            arr[s[i]-97]++;
        }

        for(int i=0;i<t.size();i++){
            arr[t[i]-97]--;
            if(arr[t[i]-97]<0){
                return false;
            }
        }

        for(int i=0;i<26;i++){
            if(arr[i]!=0){
                return false;
            }
        }

        return true;
    }
};