Write a function to check whether two strings are anagrams of each other.
Two strings are anagrams if they contain the same characters with the same counts. Compare Counter(a) with Counter(b) in O(n) time, or compare sorted(a) with sorted(b) in O(n log n) time.
Explain it simply
"listen" and "silent" use the same letters, just in a different order. So order does not matter; counts do.
Line by line
from collections import Counter
def is_anagram(a, b):
a = a.replace(" ", "").lower()
b = b.replace(" ", "").lower()
return Counter(a) == Counter(b)
def is_anagram_sorted(a, b):
return sorted(a.lower()) == sorted(b.lower())
print(is_anagram("listen", "silent")) # Output: True
print(is_anagram("Dormitory", "dirty room")) # Output: True
print(is_anagram("abc", "abd")) # Output: False
print(is_anagram_sorted("aab", "abb")) # Output: FalseCounter builds a dictionary of letter counts, and two Counters compare equal when all counts match. The sorted version is shorter but does more work for long strings.
Complexity
Counter version: time O(n), space O(k) where k is the number of distinct characters. Sorted version: time O(n log n), space O(n).
What to say in the interview
"First check the lengths if spaces aren't ignored, since different lengths can't be anagrams. Then compare character counts with Counter. Sorting both strings also works and is easy to explain, but it is slower asymptotically."