You could utilize the fact that two anagrams when sorted will be the same:
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
Or that they would have the same counts of characters:
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
The latter is more efficient since sorting is O(n log n)
, while constructing the Counter/Dictionary/Map/HashTable is linear time i.e., O(n)
.
If you don't want to use collections.Counter
since it feels like it's abstracting away the core part of the problem, you could replicate its functionality with a list (assumes both strings will only contain lowercase characters):
class Solution:
def lowercase_counts(self, s: str) -> list[int]:
counts = [0] * 26
for ch in s:
counts[ord(ch) - ord('a')] += 1
return counts
def isAnagram(self, s: str, t: str) -> bool:
return self.lowercase_counts(s) == self.lowercase_counts(t)
Or more robustly supporting all Unicode characters using a dictionary:
class Solution:
def character_counts(self, s: str) -> dict[str, int]:
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
return counts
def isAnagram(self, s: str, t: str) -> bool:
return self.character_counts(s) == self.character_counts(t)