..
242. Valid Anagram
Question
Check if s
and t
are anagrams
First solution
- Create
{character: count}
dict for both strings and compare
O(n), O(n)
Iterate through both. Iterate for searching. Store both strings as lists
dict_s = {}
dict_t = {}
for i in s:
if i not in dict_s:
dict_s[i] = 1
else:
dict_s[i] += 1
for i in t:
if i not in dict_t:
dict_t[i] = 1
else:
dict_t[i] += 1
return (dict_s == dict_t)
Other ideas
- Sort and compare
Time of O(nlogn) but constant space
Neetcode answer
- Create two constant space dict for the form {a:count} where a is the characters of the alphabet
- Then just iterate the strings and populate the dicts
- compare dicts