Valid Anagram

Charan RCharan R
1 min read

Problem

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Click Here to read the entire problem.

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.

0
Subscribe to my newsletter

Read articles from Charan R directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Charan R
Charan R