Valid Anagram
Valid Anagram Problem Given two strings s and t, check if t is an anagram of s. An anagram means both strings contain the same characters with the same frequency, just arranged differently. Strateg...

Source: DEV Community
Valid Anagram Problem Given two strings s and t, check if t is an anagram of s. An anagram means both strings contain the same characters with the same frequency, just arranged differently. Strategy The idea is simple: Count how many times each character appears in s Then try to “cancel out” those counts using t If everything balances to zero, the strings are anagrams. Code class Solution: def isAnagram(self, s, t): if len(s) != len(t): return False count = {} for ch in s: count[ch] = count.get(ch, 0) + 1 for ch in t: if ch not in count or count[ch] == 0: return False count[ch] -= 1 return True Key Lines Explained if len(s) != len(t): If lengths differ, they can’t be anagrams. count[ch] = count.get(ch, 0) + 1 Count frequency of each character in s. if ch not in count or count[ch] == 0: If a character in t doesn’t match, return False. count[ch] -= 1 Reduce count as we match characters. Why This Works Anagrams have the same characters in the same quantities. By counting and cancelling, w