242. Valid Anagram

Easy

Problem:

Determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

https://leetcode.com/problems/valid-anagram/

Solution:

Hash Table

import collections

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        s_dict = collections.defaultdict(int)
        t_dict = collections.defaultdict(int)

        if len(s) == len(t):
            for idx in range(len(s)):
                s_dict[s[idx]] += 1
                t_dict[t[idx]] += 1
            
            for char in s:
                if s_dict[char] != t_dict[char]:
                    return False
        
        else:
            return False
        
        return True

Pythonic way

import collections

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return sorted(s) == sorted(t)

Last updated