0
0
PythonProgramBeginner · 2 min read

Python Program to Check if Two Strings Are Anagram

You can check if two strings are anagrams in Python by comparing their sorted characters using sorted(str1) == sorted(str2).
📋

Examples

Inputlisten, silent
OutputTrue
Inputhello, world
OutputFalse
Inputaabbcc, abcabc
OutputTrue
🧠

How to Think About It

To check if two strings are anagrams, think about whether they have the exact same letters in the same amounts. If you sort both strings alphabetically, they should look identical if they are anagrams.
📐

Algorithm

1
Get the two input strings.
2
Sort the characters of both strings.
3
Compare the sorted versions.
4
If they are equal, return True; otherwise, return False.
💻

Code

python
def are_anagrams(str1, str2):
    return sorted(str1) == sorted(str2)

print(are_anagrams('listen', 'silent'))  # True
print(are_anagrams('hello', 'world'))    # False
Output
True False
🔍

Dry Run

Let's trace the example 'listen' and 'silent' through the code

1

Input strings

str1 = 'listen', str2 = 'silent'

2

Sort both strings

sorted(str1) = ['e', 'i', 'l', 'n', 's', 't'], sorted(str2) = ['e', 'i', 'l', 'n', 's', 't']

3

Compare sorted lists

Both sorted lists are equal

4

Return result

Return True because the strings are anagrams

Iterationsorted(str1)sorted(str2)Are equal?
Final['e', 'i', 'l', 'n', 's', 't']['e', 'i', 'l', 'n', 's', 't']True
💡

Why This Works

Step 1: Sorting strings

Sorting rearranges the letters in both strings so they can be compared easily.

Step 2: Comparing sorted strings

If the sorted lists of characters are the same, the strings have the same letters in the same amounts.

Step 3: Return boolean result

Return True if they match, meaning the strings are anagrams; otherwise, return False.

🔄

Alternative Approaches

Using collections.Counter
python
from collections import Counter

def are_anagrams(str1, str2):
    return Counter(str1) == Counter(str2)

print(are_anagrams('listen', 'silent'))  # True
print(are_anagrams('hello', 'world'))    # False
This method counts each character's frequency and compares counts, which can be faster for large strings.
Manual counting with dictionary
python
def are_anagrams(str1, str2):
    if len(str1) != len(str2):
        return False
    count = {}
    for ch in str1:
        count[ch] = count.get(ch, 0) + 1
    for ch in str2:
        if ch not in count or count[ch] == 0:
            return False
        count[ch] -= 1
    return True

print(are_anagrams('listen', 'silent'))  # True
print(are_anagrams('hello', 'world'))    # False
This approach manually tracks character counts without extra imports but is more code.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting both strings takes O(n log n) time where n is the length of the strings.

Space Complexity

Sorting creates new lists of characters, so it uses O(n) extra space.

Which Approach is Fastest?

Using collections.Counter runs in O(n) time and is faster for large strings, but sorting is simpler and good for small inputs.

ApproachTimeSpaceBest For
Sorting with sorted()O(n log n)O(n)Simple and small strings
Counting with collections.CounterO(n)O(n)Large strings, better performance
Manual counting with dictionaryO(n)O(n)No imports, manual control
💡
Use sorted() for a quick and simple anagram check on small strings.
⚠️
Forgetting to handle case sensitivity or spaces can cause incorrect results.