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
Solution Time Space
Sorting O(nlogn+mlogm) O(1) or O(n+m)
Hash table O(n+m) O(1) since max 26 different chars
Hash table (optimal) O(n+m) O(1)