Skip to main content

242. Valid Anagram

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.

Solution

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False

sc, tc = {}, {}
for idx in range(len(s)):
sc[s[idx]] = 1 + sc.get(s[idx], 0)
tc[t[idx]] = 1 + tc.get(t[idx], 0)
return sc == tc

Time Complexity: O(n), where n is the length of the strings

Space Complexity: O(n), where n is the length of the strings

Explanation

The idea is to check that the frequency of any given letter is equal across both input strings.

This can be done manually, as can be seen in the first tab, by simply traversing the strings at the same time and updating a frequency dictionary for each as you go.

The code can be made simpler by using "defaultdict(int)" instead of "{}" to make the assignment on the dictionary editing lines 8 & 9 "+=1".

Another approach is to use the Counter() function on both input strings and then simply compare the dictionaries containing the frequencies. However, this might not be allowed.