Check for Anagrams in Python

Two strings are anagrams if they contain the same characters in the same frequency, just in a different order. For example, “listen” and “silent” are anagrams.

Solution 1: Sort and Compare

def is_anagram(s1, s2):
    return sorted(s1.lower()) == sorted(s2.lower())

print(is_anagram("listen", "silent"))  # True
print(is_anagram("hello", "world"))    # False

Solution 2: Using Counter (Most Pythonic)

from collections import Counter

def is_anagram_counter(s1, s2):
    return Counter(s1.lower()) == Counter(s2.lower())

print(is_anagram_counter("Triangle", "Integral"))  # True

Solution 3: Manual Character Count

def is_anagram_manual(s1, s2):
    if len(s1) != len(s2):
        return False
    count = {}
    for ch in s1.lower():
        count[ch] = count.get(ch, 0) + 1
    for ch in s2.lower():
        count[ch] = count.get(ch, 0) - 1
    return all(v == 0 for v in count.values())

print(is_anagram_manual("Astronomer", "Moon starer"))  # False (has space)

Key Takeaway

The Counter approach is the cleanest and most interview-friendly. Always remember to normalize case with .lower() and handle spaces/punctuation as needed.

(Visited 1 times, 1 visits today)