Anagram Check

Medium · rating 1200 · strings, sorting

Read two lines, strings a and b. Print YES if they are anagrams of each other (same characters in any order), otherwise NO.

Editorial

Valid Anagram is a classic string interview question: two strings are anagrams when one is a rearrangement of the other — which happens exactly when they share the same characters with the same frequencies.

Approach

Tally the characters of the first string, then subtract using the second. If a length differs or any count drops below zero, they aren't anagrams. A 26-slot array (lowercase letters) or a hash map both work.

if len(a) != len(b): return False
count = Counter(a)
for c in b:
    count[c] -= 1
    if count[c] < 0: return False
return True

Alternative

Sorting both strings and comparing also works in O(n log n); frequency counting is the faster O(n) route.

Complexity

Time: O(n). Space: O(1) for a fixed alphabet.

Open Anagram Check in Code Arena →