Problem
Given two strings s and t, return True if t is an anagram of s, otherwise False.
An anagram means both strings contain the same characters with the same frequency.
Code
class Solution(object):
def isAnagram(self, s, t):
if len(s) != len(t):
return False
count = [0] * 26
for i in range(len(s)):
count[ord(s[i]) - ord('a')] += 1
count[ord(t[i]) - ord('a')] -= 1
return all(c == 0 for c in count)
Step-by-Step Explanation
1. Length Check
if len(s) != len(t):
return False
If the strings have different lengths, they cannot be anagrams because anagrams must use all characters.
2. Create Count Array
count = [0] * 26
We create a list of size 26 to represent each lowercase letter from 'a' to 'z'.
Each index corresponds to a character:
index 0 → 'a'
index 1 → 'b'
...
index 25 → 'z'
This allows us to store frequency counts efficiently.
3. Loop Through Strings
for i in range(len(s)):
We iterate through both strings once, which keeps the time complexity linear.
4. Use ord() to Map Characters to Index
count[ord(s[i]) - ord('a')] += 1
count[ord(t[i]) - ord('a')] -= 1
What is ord()?
ord(character) returns the ASCII (integer) value of a character.
Examples:
ord('a') = 97
ord('b') = 98
Why subtract ord('a')?
This converts characters into indices from 0 to 25.
Example:
'a' → 97 - 97 = 0
'b' → 98 - 97 = 1
'z' → 122 - 97 = 25
So each character maps directly to a position in the array.
Why increment and decrement?
For string s, we increment the count
For string t, we decrement the count
If both strings have identical character frequencies, all values in the array will end up as zero.
5. Final Check
return all(c == 0 for c in count)
This checks whether every value in the count array is zero.
If yes, the strings are anagrams. Otherwise, they are not.
Why This Approach is Better
Time Complexity
The algorithm runs in O(n) time because it loops through the strings once.
Space Complexity
It uses a fixed-size array of 26 elements, so space complexity is O(1).
Efficiency
This method avoids sorting, which would take O(n log n) time. It is therefore faster and more optimal.
Key Idea
Instead of rearranging characters, we track how many times each character appears and compare the counts efficiently.
Top comments (0)