Given two strings, determine if one is an anagram of the other. Two strings are anagrams if they contain the same characters with the same frequencies, just in a different order.
isAnagram(s, t)
Input format: two space-separated words on one line.
isAnagram("listen", "silent") // → true
isAnagram("hello", "world") // → false
isAnagram("abc", "bca") // → true
isAnagram("a", "a") // → true
Two strings are anagrams if they're made of the same characters, the same number of times each, just rearranged. Order doesn't matter at all — it's purely about whether the two strings have matching character counts.
You could sort both strings and compare the results. That works, but sorting costs O(n log n), and you'd pay it twice. There's no need to impose an order just to compare frequencies — this is a counting problem, not an ordering one.
If two strings are anagrams, every character appears the same number of times in both. So build a tally of character counts for one string, then check the other string matches that tally exactly.
Comparing two separately-built frequency maps means checking every key in both. Decrementing a single map while consuming the second string collapses "build and compare" into one pass, with an early exit the moment something doesn't fit — like filling a bucket, then draining it, and checking you never try to drain more than exists.
Any problem comparing the multiset of two collections — regardless of order — reduces to counting. Tallying frequencies is usually cheaper and more direct than sorting, especially when you can consume one map while scanning the second for an early exit.
def is_anagram(s, t):
if len(s) != len(t):
return False
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
for ch in t:
next_count = freq.get(ch, 0) - 1
if next_count < 0:
return False
freq[ch] = next_count
return True
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.