Easy
003Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram uses every character from the original string exactly once.
EXAMPLES
Example 1
Input
{
"s": "anagram",
"t": "nagaram"
}
Output
trueFUNCTION SHAPE
s: stringt: string→boolSOLUTION NOTE
There are a few ways to do this using sorting and counters. The O(n log n) sorting approach is also valid.
Reveal reference solution +
pythonREFERENCE
# Method 1: Compare sorted counters
def isAnagram(self, s: str, t: str) -> bool:
return sorted(Counter(s).items()) == sorted(Counter(t).items())
# Method 2: Compare sorted strings
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
# Method 3: Compare counters directly
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
# Method 4: Decrement counter
def isAnagram(self, s: str, t: str) -> bool:
freq = Counter(s)
for c in t:
freq[c] -= 1
if freq[c] == 0:
del freq[c]
return not freqTime
O(n+m)Space
O(n+m)