Problem Description
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
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.
Example 1:
- Input:
s = "anagram", t = "nagaram" - Output:
true
Example 2:
- Input:
s = rat", t = "car" - Output:
false
My Idea
Since anagrams contain the same letters, my initial idea was to just sort the two strings and compare them. This results in a time complexity of O(nlog(n)) due to the sorting, but ist a very short solution consisting of just one line. My next approach was creating a dict containing the frequency of all the chars of every string and comparing them. This results in a time complexity of O(n).
My solution
def isAnagram(s: str, t: str) -> bool:
ds=dict()
for i in s:
if i in ds:
ds[i]+=1
else:
ds[i]=1
dt=dict()
for j in t:
if j in dt:
dt[j]+=1
else:
dt[j]=1
return ds==dt
# One-liner with O(nlogn) time complexity and O(n) space complexity
def isAnagramShort(s: str, t: str) -> bool:
return sorted(s) == sorted(t)