PracticeNeetCode ↗LeetCode ↗
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
s's "signature"; t must consume that signature exactly.t (instead of building a second map and comparing at the end) lets you fail fast.len(s) != len(t), return False right away.s.t, decrementing the count for each character; if a character is missing from the map or its count is already 0, return False.t is fully consumed without a mismatch, return True.Time: O(n) — Space: O(n)
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = {}
for ch in s:
count[ch] = count.get(ch, 0) + 1
for ch in t:
if ch not in count or count[ch] == 0:
return False
count[ch] -= 1
return TrueHow the solution above works, piece by piece.
if len(s) != len(t): return False: different lengths can never be anagrams, and this check makes the later logic safe.s in a dictionary, count[ch] = count.get(ch, 0) + 1.t. If a letter is missing or its count is already 0, t has more of it than s → False.count[ch] -= 1.t was paid for and the lengths match, every count ends at exactly 0, so it is an anagram. O(n) time; the dictionary has at most 26 keys, so O(1) extra space.Running it on s = "anagram", t = "nagaram":
s. Each letter of t uses up one count (blue = the count just decreased). Nothing ever goes below zero, so the answer is True.