DEV Community

WhereIsLijah
WhereIsLijah

Posted on

242. Valid Anagram

Topic: Array & Hashing

Soln 1 (dictonary solution):

  1. Compare the lengths of both strings.
  2. If they are not the same length, they are not anagrams.
  3. Create a new dictionary called count.
  4. Loop through the characters in s:
  5. If the character already exists in the dictionary, then increment its value by 1.
  6. Else, assign the value of the key to 1.
  7. Loop through the characters in t:
  8. If the character does not exist in the dictionary or the character count is 0, then return False.
  9. Else, decrement the value of the character by 1.
  10. Return True.
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False

        count = {}

        for char in s:
            if char in count:
                count[char]+=1
            else:
                count[char] = 1

        for char in t:
            if char not in count or count[char] == 0:
                return False
            count[char]-=1
        return True 

Enter fullscreen mode Exit fullscreen mode

Soln 2 (set solution):

  1. Compare the lengths of both strings.
  2. If they are not the same length, they are not anagrams.
  3. Loop through the characters in the set of s (set removes the duplicates):
  4. If the count of any character in s is not equal to the count of the same character in t:
  5. then return False.
  6. If all character counts match, then the strings are anagrams (return True).
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False 
        for i in set(s): 
            if s.count(i) != t.count(i):
                return False
        return True   
Enter fullscreen mode Exit fullscreen mode

Soln 3:
A very obvious solution:

  1. Alphabetically sort both strings (s, t) and compare them. Returns True if they both are the same length and contain the same characters, else False if they do not. (Yes, all on the same line.)
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return sorted(s) == sorted(t)
Enter fullscreen mode Exit fullscreen mode

Notes:
Sets & dictionaries are unordered and unique, although dictionaries can contain duplicates values

Top comments (0)