Valid Anagram
Given two strings s
and t
, return true
if the two strings are anagrams of each other, otherwise return false
.
Hash table
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_f, t_f = {}, {}
for i in range(len(s)):
s_f[s[i]] = 1 + s_f.get(s[i], 0)
t_f[s[i]] = 1 + t_f.get(t[i], 0)
return s_f == t_f
Optimal hash table
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26
for i in range(len(s)):
count[ord(s[i]) - ord('a')] += 1
count[ord(t[i]) - ord('a')] -= 1
for val in count:
if val != 0:
return False
return True
- Memory efficient - Using fixed-size array, no further memory allocation needed
- Array > Hash map operations, requires comparing dictionaries
- Single array to track both strings, incrementing and decrementing for s and t characters respectively
Solution | Time | Space |
---|---|---|
Sorting | ||
Hash table | ||
Hash table (optimal) |