Question: https://leetcode.com/problems/valid-anagram/description/
First I thought this question shouldn’t be in the easy label.
When I read it correctly 4-5 times I understood it.
I thought this was a simple question I just converted the strings to set and compared if they are same.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if(set(s) == set(t)):
return True
return False
But I didn’t thought what for cases like this: s="aa”, t="a”. My answer would return True but it is False.
So, I added a length check next:
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if(len(s)== len(t)):
if(set(s) == set(t)):
return True
return False
But, what for cases like: s=”aacc”, t=”ccac”. My answer would be True but it is False.
Finally, I was able to process what the question wanted to say.
I compared the length of the 2 strings. If they matched I would compare the sorted lists of both the strings and if they matched I would return True else would return False.
This one worked out for all the possible cases.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if(len(s)== len(t)):
s_l = list(s)
t_l = list(t)
s_l.sort()
t_l.sort()
if s_l == t_l:
return True
return False
I guess I either love O(n log n) or sorting. There were other ways to do this too.
In this one, I can keep adding all characters as keys in a dictionary and increment the count by one if it repeats.
Reduce the occurrences if it turns out to be there in another string.
If all the values in the turn out to be zero. It is an Anagram. else it isn’t.
Create an array with 26 0’s. Increase the counter of the particular element whenever the character occurs in the string. And decrement if it occurs in the second string. And that’s it.