Python Program to Check if Two Strings Are Anagram
sorted(str1) == sorted(str2).Examples
How to Think About It
Algorithm
Code
def are_anagrams(str1, str2): return sorted(str1) == sorted(str2) print(are_anagrams('listen', 'silent')) # True print(are_anagrams('hello', 'world')) # False
Dry Run
Let's trace the example 'listen' and 'silent' through the code
Input strings
str1 = 'listen', str2 = 'silent'
Sort both strings
sorted(str1) = ['e', 'i', 'l', 'n', 's', 't'], sorted(str2) = ['e', 'i', 'l', 'n', 's', 't']
Compare sorted lists
Both sorted lists are equal
Return result
Return True because the strings are anagrams
| Iteration | sorted(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
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
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
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sorting with sorted() | O(n log n) | O(n) | Simple and small strings |
| Counting with collections.Counter | O(n) | O(n) | Large strings, better performance |
| Manual counting with dictionary | O(n) | O(n) | No imports, manual control |
sorted() for a quick and simple anagram check on small strings.