Problem
Valid AnagramGiven two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
Click the above card to go to the problem on leetcode.
Approach
What he heck is an anagram?
cat
and tac
are words that have been rearranged using the same alphabets. Now that’s an anagram.
So, we are given two strings and we need to check if they are anagrams or not.
We are going to use a hashmap to solve this question, since the letters are only rearranged in an anagram - we can easily take the count of how many occurrences each word has and then compare them.
Solution
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
char_s = {}
char_t = {}
for char in s:
char_s[char] = char_s.get(char, 0) +1
for char in t:
char_t[char] = char_t.get(char, 0) +1
return char_s == char_t
Look at how I am using get()
to fetch the character and the count of the occurrences? It’s a pretty neat trick - quick and easy.
That’s it.
the .get() when using a hashmap is somewhat of a lifesaver. Trust me, you’ll be using it in a lot of places. So, get familiar with it, see how you can use it in multiple scenarios.