How do you check whether two strings are anagrams of each other?
Two strings are anagrams when they contain exactly the same characters with exactly the same counts. The direct check is to build a frequency table for the first string and then walk the second string, decrementing the counts. If any count would go negative, the strings differ; if every character is consumed without a shortfall, they match.
def is_anagram(a, b):
if len(a) != len(b):
return False
counts = {}
for char in a:
counts[char] = counts.get(char, 0) + 1
for char in b:
if char not in counts:
return False
counts[char] -= 1
if counts[char] < 0:
return False
return True
print(is_anagram("listen", "silent"))
print(is_anagram("listen", "silentx"))The outputs are True and False. The second call fails on the length check before the loop even starts, which is the cheapest way to reject a mismatch.
The mechanism is that the frequency table turns the question of whether the two multisets are equal into a question you can answer one character at a time. It is a single pass over each string, so the time is O of n where n is the length, and the space is O of k where k is the number of distinct characters, which is bounded by the alphabet size for typical text.
The trade-off to name is the space. The count table uses memory proportional to the alphabet, while the sorted-signature approach also needs memory because sorting produces a new list. If you need to run this check over millions of pairs, the practical cost is dominated by the allocation, and a single reusable counter or a bytes comparison after sorting may be faster in practice. The count approach is also the one to reach for when you only want to compare a handful of strings, since it is the clearest to read.