Python Program to Check If Two Strings are Anagram

Updated on December 5, 2024
Check if two strings are anagram header image

Introduction

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word 'listen' can be rearranged into 'silent'. Determining if two strings are anagrams is a common problem in computer science, often used to test the understanding of string manipulation and sorting algorithms.

In this article, you will learn how to verify if two strings are anagrams of each other using Python. Through a series of examples, you'll explore different methods to achieve this, starting from a simple sorting method to more advanced techniques involving dictionaries.

Verifying Anagrams by Sorting

Basic Method Using Sorting

  1. Convert both strings to the same case (lower or upper) for a case-insensitive comparison.

  2. Sort the characters of both strings.

  3. Compare the sorted versions of both strings to check if they are anagrams.

    python
    def are_anagrams(s1, s2):
        return sorted(s1.lower()) == sorted(s2.lower())
    
    # Example usage
    print(are_anagrams("Listen", "Silent"))  # Output: True
    print(are_anagrams("Hello", "World"))  # Output: False
    

    This function converts both input strings to lowercase, sorts them, and checks for equality. If both sorted strings are the same, they are anagrams.

Optimizing with Early Exit

  1. After case normalization, check if both strings have the same length; if not, return False immediately.

  2. Sort and compare the strings as in the basic method.

    python
    def are_anagrams_optimized(s1, s2):
        if len(s1) != len(s2):
            return False
        return sorted(s1.lower()) == sorted(s2.lower())
    
    # Example usage
    print(are_anagrams_optimized("Listen", "Silent"))  # Output: True
    print(are_anagrams_optimized("Hello", "World"))  # Output: False
    

    Here, an early check on string lengths avoids unnecessary sorting if the strings are already of different lengths, enhancing performance.

Using Dictionaries to Count Characters

Counting Characters with Dictionary

  1. Use a dictionary to count each character in the first string.

  2. Decrement the count for each character found in the second string.

  3. Ensure all counts in the dictionary are zero at the end.

    python
    def are_anagrams_dict(s1, s2):
        if len(s1) != len(s2):
            return False
    
        char_count = {}
        for char in s1.lower():
            if char in char_count:
                char_count[char] += 1
            else:
                char_count[char] = 1
    
        for char in s2.lower():
            if char in char_count:
                char_count[char] -= 1
            else:
                return False
    
        return all(count == 0 for count in char_count.values())
    
    # Example usage
    print(are_anagrams_dict("Listen", "Silent"))  # Output: True
    print(are_anagrams_dict("Hello", "World"))    # Output: False
    

    This code snippet also includes a dictionary to track character frequencies in s1 and then decrements those frequencies based on characters in s2. Finally, it checks if all counts are zero, confirming an anagram.

Conclusion

Determining if two strings are anagrams in Python can be approached in various ways, each with its trade-offs in terms of simplicity and performance. Sorting the strings is straightforward but might not be the most efficient for very long strings or repetitive checks. Using dictionaries provides a more scalable solution by counting character occurrences directly, which can be more efficient than sorting for large datasets. Whichever method you choose, understanding these basic string operations is crucial for tackling more complex problems in Python programming.