Python Anagram Checker

Check if two strings are anagrams by comparing their character compositions in Python.

Try Python Anagram Checker Code

How it Works

Two strings are anagrams if they contain the same characters in identical frequencies, though arranged in a different order (e.g., "listen" and "silent").

An elegant way to check for anagrams is to clean the strings (strip whitespace and lower casing), sort their characters, and verify if the sorted lists are identical.

This sorting approach executes in O(k log k) time where k is the string length, which is optimal for short text checks.

Source Code

Checking word pairings for anagram status by letter sorting.

anagram.py
Try in Editor
def is_anagram(str1, str2):
    s1 = sorted(str1.lower().replace(" ", ""))
    s2 = sorted(str2.lower().replace(" ", ""))
    return s1 == s2

word1, word2 = "listen", "silent"
print(f"Are '{word1}' and '{word2}' anagrams? {is_anagram(word1, word2)}")

word3, word4 = "hello", "world"
print(f"Are '{word3}' and '{word4}' anagrams? {is_anagram(word3, word4)}")
Terminal Output
Are 'listen' and 'silent' anagrams? True
Are 'hello' and 'world' anagrams? False

Real-world Applications

  • Text analysis and linguistic comparison engines
  • String puzzle design and validator systems
  • Technical interview coding tasks

Frequently Asked Questions

Is there a way to solve this in O(n) linear time?

Yes! Instead of sorting, you can count letter frequencies using a hash map or Python's `collections.Counter` and compare the resulting frequency maps.

More Examples