Valid Anagram in Python

Anagrams are words or phrases formed by rearranging the letters of another word or phrase, using all the original letters exactly once. For example, "ANAGRAM" and "NAAGARM" are anagrams because they contain the same letters in different arrangements, but "cat" and "fat" are not anagrams because they have different letters.

To check if two strings are valid anagrams, we can use several approaches. The most common method is to sort the characters of both strings and compare them.

Method 1: Using Sorting

Convert both strings to sorted character lists and compare them ?

def is_anagram_sorting(s, t):
    """
    Check if two strings are anagrams using sorting approach
    """
    # If lengths are different, they can't be anagrams
    if len(s) != len(t):
        return False
    
    # Sort both strings and compare
    return sorted(s.lower()) == sorted(t.lower())

# Test examples
print(is_anagram_sorting("ANAGRAM", "NAAGARM"))
print(is_anagram_sorting("listen", "silent"))
print(is_anagram_sorting("cat", "fat"))
True
True
False

Method 2: Using Character Frequency Count

Count the frequency of each character in both strings ?

def is_anagram_frequency(s, t):
    """
    Check if two strings are anagrams using character frequency
    """
    if len(s) != len(t):
        return False
    
    # Count character frequencies
    char_count = {}
    
    # Count characters in first string
    for char in s.lower():
        char_count[char] = char_count.get(char, 0) + 1
    
    # Subtract character counts from second string
    for char in t.lower():
        if char not in char_count:
            return False
        char_count[char] -= 1
        if char_count[char] == 0:
            del char_count[char]
    
    # If all characters are balanced, dictionary should be empty
    return len(char_count) == 0

# Test examples
print(is_anagram_frequency("ANAGRAM", "NAAGARM"))
print(is_anagram_frequency("race", "care"))
print(is_anagram_frequency("hello", "world"))
True
True
False

Method 3: Using Python Counter

Use the built-in Counter class for cleaner frequency counting ?

from collections import Counter

def is_anagram_counter(s, t):
    """
    Check if two strings are anagrams using Counter
    """
    return Counter(s.lower()) == Counter(t.lower())

# Test examples
print(is_anagram_counter("ANAGRAM", "NAAGARM"))
print(is_anagram_counter("dormitory", "dirty room"))
print(is_anagram_counter("python", "java"))
True
False
False

Comparison

Method Time Complexity Space Complexity Best For
Sorting O(n log n) O(1) Simple implementation
Frequency Count O(n) O(k) Large strings
Counter O(n) O(k) Clean readable code

Conclusion

Use the sorting method for simple cases and readability. For better performance with large strings, use the frequency counting approach. The Counter method provides the cleanest and most Pythonic solution.

Updated on: 2026-03-25T07:14:20+05:30

740 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements