Skip to content

242. Valid Anagram

Problem Statement

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

NOTE: 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.

Examples

Example 1:

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

Example 2:

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

Constraints

  • 1<= s.length, t.length <=5104
  • s and t consist of lowercase English letters.

Submissions

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

        countS, countT = {}, {}
        for char in s:
            countS[char] = 1 + countS.get(char, 0)
        for char in t:
            countT[char] = 1 + countT.get(char, 0)

        return countS == countT

Explanations

Python
Submitted by @noeyislearning
  • class Solution:: This is the class that contains the function containsDuplicate.
  • def isAnagram(self, s: str, t: str) -> bool:: This function takes two strings s and t as input and returns a boolean value.
  • if len(s) != len(t): return False: If the lengths of the two strings are not equal, return False.
  • return sorted(s) == sorted(t): Sort the characters in both strings and compare them. If the sorted strings are equal, return True; otherwise, return False.
Python
Submitted by @noeyislearning