DEV Community

Tharunya K R
Tharunya K R

Posted on

Check if Two Strings Are Anagrams

Problem

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

An anagram means both strings contain the same characters with the same frequency, but possibly in a different order.

Example

Input
s = "anagram"
t = "nagaram"

Output
True

Input
s = "rat"
t = "car"

Output
False

Approach

Sort both strings.
Compare the sorted strings.
If they are equal → Anagram (True)
Otherwise → Not an Anagram (False)

Python Code

from collections import Counter

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

Output
True

Top comments (0)