Check whether two strings are anagram of each other in Python

Two strings are anagrams if they contain the same characters with the same frequency, just rearranged. For example, "bite" and "biet" are anagrams because both contain one 'b', one 'i', one 't', and one 'e'.

We'll explore three different methods to check if two strings are anagrams in Python.

Method 1: Using Sorting

The simplest approach is to sort both strings and compare them ?

def check_anagram_sorting(s, t):
    if len(s) != len(t):
        return False
    
    s_sorted = sorted(s)
    t_sorted = sorted(t)
    
    return s_sorted == t_sorted

s = "bite"
t = "biet"
print(f"'{s}' and '{t}' are anagrams: {check_anagram_sorting(s, t)}")

# Test with non-anagrams
s2 = "hello"
t2 = "world"
print(f"'{s2}' and '{t2}' are anagrams: {check_anagram_sorting(s2, t2)}")
'bite' and 'biet' are anagrams: True
'hello' and 'world' are anagrams: False

Method 2: Using Character Count

Count the frequency of each character in both strings ?

def check_anagram_count(s, t):
    if len(s) != len(t):
        return False
    
    char_count = {}
    
    # Count characters in first string
    for char in s:
        char_count[char] = char_count.get(char, 0) + 1
    
    # Subtract counts for second string
    for char in t:
        if char not in char_count:
            return False
        char_count[char] -= 1
        if char_count[char] == 0:
            del char_count[char]
    
    return len(char_count) == 0

s = "bite"
t = "biet"
print(f"'{s}' and '{t}' are anagrams: {check_anagram_count(s, t)}")

s2 = "listen"
t2 = "silent"
print(f"'{s2}' and '{t2}' are anagrams: {check_anagram_count(s2, t2)}")
'bite' and 'biet' are anagrams: True
'listen' and 'silent' are anagrams: True

Method 3: Using Counter from collections

Python's Counter class makes character counting even simpler ?

from collections import Counter

def check_anagram_counter(s, t):
    return Counter(s) == Counter(t)

s = "bite"
t = "biet"
print(f"'{s}' and '{t}' are anagrams: {check_anagram_counter(s, t)}")

# Test with case sensitivity
s2 = "Listen"
t2 = "Silent"
print(f"'{s2}' and '{t2}' are anagrams: {check_anagram_counter(s2.lower(), t2.lower())}")
'bite' and 'biet' are anagrams: True
'Listen' and 'Silent' are anagrams: True

Comparison

Method Time Complexity Space Complexity Best For
Sorting O(n log n) O(1) Simple implementation
Character Count O(n) O(k) Better performance
Counter O(n) O(k) Clean, readable code

Note: n = string length, k = number of unique characters

Conclusion

Use the sorting method for simple cases, the manual counting approach for better performance, or Counter for the most readable solution. All methods effectively determine if two strings are anagrams by comparing character frequencies.

Updated on: 2026-03-25T14:43:37+05:30

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements