Python Program to Check Anagram with Examples and Explanation
sorted(str1) == sorted(str2).Examples
How to Think About It
Algorithm
Code
def are_anagrams(str1, str2): return sorted(str1.lower()) == sorted(str2.lower()) 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'
Convert to lowercase
str1.lower() = 'listen', str2.lower() = 'silent'
Sort characters
sorted('listen') = ['e', 'i', 'l', 'n', 's', 't'], sorted('silent') = ['e', 'i', 'l', 'n', 's', 't']
Compare sorted lists
['e', 'i', 'l', 'n', 's', 't'] == ['e', 'i', 'l', 'n', 's', 't'] -> True
| Step | Sorted str1 | Sorted str2 | Are Equal? |
|---|---|---|---|
| 1 | ['e', 'i', 'l', 'n', 's', 't'] | ['e', 'i', 'l', 'n', 's', 't'] | True |
Why This Works
Step 1: Lowercase conversion
Using lower() makes the comparison case-insensitive, so 'Listen' and 'silent' match.
Step 2: Sorting characters
Sorting rearranges letters alphabetically, so anagrams become identical sequences.
Step 3: Comparing sorted lists
If sorted lists are equal, the original strings have the same letters in the same counts, confirming an anagram.
Alternative Approaches
from collections import Counter def are_anagrams(str1, str2): return Counter(str1.lower()) == Counter(str2.lower()) print(are_anagrams('listen', 'silent')) # True print(are_anagrams('hello', 'world')) # False
def are_anagrams(str1, str2): str1, str2 = str1.lower(), str2.lower() 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 all(v == 0 for v in count.values()) 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, which dominates the runtime.
Space Complexity
Sorting creates new lists of characters, so extra space proportional to the string length is used.
Which Approach is Fastest?
Using collections.Counter runs in O(n) time and is faster for long strings, but sorting is simpler and often sufficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sorting and comparing | O(n log n) | O(n) | Simple and short strings |
| collections.Counter | O(n) | O(n) | Long strings with many characters |
| Manual counting | O(n) | O(n) | When avoiding imports or for learning purposes |