Leetcode problem 242 — Valid Anagram with Best Solution

B M Mahmud
2 min readMay 16, 2022

The problem valid anagram is an Array and Hashing type problem. Here, we will understand the question and solve it.

MAHMUD

Problem:

Here the problem description is,

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example:

Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false

Solution:

As a basic process, if we want to check what process we will follow?

First, we will check does both have the same number of characters.

Input: s = "anagram", t = "nagaram"
s = 7 and t = 7

then, we will check the number of character repeated how my times.

s = "anagram" >> a = 3, n = 1, g = 1, r =1, m = 1
t = "nagaram" >> n = 1, a = 3, g = 1, r = 1, m = 1

If both counts are the same then we can turn True, which means Anagram. Otherwise, we can say False.

Now, Implement this logic in code:

def isAnagram(s: str, t: str) -> bool:    if len(s) != len(t):        return False ## check both length is equal or not    countS, countT = {}, {}     for i in range(len(s)): ## count character       countS[s[i]] = 1 + countS.get(s[i], 0)       countT[t[i]] = 1 + countT.get(t[i], 0)    for c in countS:  ## check both have same numbers of characters        if countS[c] != countT.get(c, 0):               return False    return True

let’s see the better way that has more time and space efficiency.

def isAnagram(s: str, t: str) -> bool:    hash = defaultdict(int)    for c in s:        hash[c] += 1    for c in t:        
hash[c] -= 1
for c, v in hash.items(): if v != 0: return False return True

Hope these two easy solutions helped you to understand the problem.

Stay connected to get more solutions with Interview tips for FANNG.

--

--

B M Mahmud

Hi, I am Mahmud. I love to share my ideas and learning strategies. You know, Sharing is caring. To know me more, check out my all links, bio.info/imash