Problem Statement
Given two strings s and t, determine if t is an anagram of s. An anagram means that t is formed by rearranging the letters of s using all original letters exactly once.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Constraints:
1 <= s.length, t.length <= 5 * 10^4
s and t consist of lowercase English letters.
Approach
We can efficiently check for anagrams by counting the frequency of each character in both strings. If the counts match t is an anagram of s.
Python Code
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# If lengths are different, they can't be anagrams
if len(s) != len(t):
return False
# Count the frequency of characters in both strings
return Counter(s) == Counter(t)
Explanation:
First, we check if the lengths of s and t are the same. Different lengths mean they cannot be anagrams.
We use Counter from Python's collections module to count how many times each character appears in both strings.
If both counters are equal, the strings are anagrams. Otherwise, they are not.
Top comments (0)