Table of contents
Valid Anagram
Problem Link:
https://leetcode.com/problems/valid-anagram/description/
My approach:
I used the concept of hashing.
You can use hashmap or in this case just a simple array of size 26.
Iterate through 's' string and update hash array by increasing the value of alphabets.
Iterate through 't' string and update hash array by decreasing the value of alphabets.
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;
}
};