You are given two strings s
and t
, determine if t
is an anagram of s
.
An anagram is a word formed by rearranging the letters of another word.
Write a function isAnagram(s: str, t: str) -> bool
to 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
One simple approach to solve this problem is to compare the sorted versions of the two input strings.
s
and t
are anagrams, then their sorted versions should be equal.s
and t
are not anagrams, then their sorted versions will be different.s
and t
are equal. If they are not equal, return False
as they cannot be anagrams.s
and t
using the in-built sorting function.s
and t
. If they are equal, return True
, else return False
.Since sorting the strings takes O(nlogn)
time complexity, this approach has a time complexity of O(nlogn)
, where n
is the length of the strings s
and t
.
Here is the Python implementation of the algorithm:
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
sorted_s = sorted(s)
sorted_t = sorted(t)
return sorted_s == sorted_t
# Example 1
s = "anagram"
t = "nagaram"
print(isAnagram(s, t))
# Output: True
# Example 2
s = "rat"
t = "car"
print(isAnagram(s, t))
# Output: False
The function returns the expected output for both examples, confirming that it is correctly determining if t
is an anagram of s
.