def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t)
print("Test 1:", isAnagram("racecar", "carrace"))
print("Test 2:", isAnagram("jar", "jam"))
Test 1: True
Test 2: False
December 17, 2024
Given two strings s
and t
, determine if they are anagrams of each other.
Example 1:
Input: s = "racecar", t = "carrace"
Output: true
Explanation: Both strings contain exactly the same characters: 'a', 'c', 'c', 'e', 'r', 'r'
The most intuitive approach might be to sort both strings and compare them:
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t)
print("Test 1:", isAnagram("racecar", "carrace"))
print("Test 2:", isAnagram("jar", "jam"))
Test 1: True
Test 2: False
Overall:
- Time Complexity: O(n \log n)
- Space Complexity: O(n) for creating new sorted strings
We can achieve better time complexity using a character frequency counter:
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
char_count = [0] * 26
for i in range(len(s)):
char_count[ord(s[i]) - ord('a')] += 1
char_count[ord(t[i]) - ord('a')] -= 1
return all(count == 0 for count in char_count)
print("Test 1:", isAnagram("racecar", "carrace"))
print("Test 2:", isAnagram("jar", "jam"))
Test 1: True
Test 2: False
Overall: - Time Complexity: O(n) - Space Complexity: O(1) (fixed size array)
or alternatively:
The Counter approach has some key implementation details worth understanding:
Overall:
- Time Complexity: O(n) where n is the length of the strings
- Space Complexity: O(k) where k is the size of the character set (26 for lowercase letters)
For cases where we might have a larger character set (not just lowercase letters), we can use a hash map:
from collections import defaultdict
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
char_count = defaultdict(int)
for s_char, t_char in zip(s, t):
char_count[s_char] += 1
char_count[t_char] -= 1
return all(count == 0 for count in char_count.values())
print("Test 1:", isAnagram("racecar", "carrace"))
print("Test 2:", isAnagram("jar", "jam"))
Test 1: True
Test 2: False
Overall:
- Time Complexity: O(n)
- Space Complexity: O(k) where k is the character set size
Approach | Time Complexity | Space Complexity | Best Used When |
---|---|---|---|
Sorting | O(n \log n) | O(n) | Simple solution needed |
Array Counter | O(n) | O(1) | Known small character set |
Hash Map | O(n) | O(k) | Large/unknown character set |
[1] Valid Anagram
[2] LeetCode Valid Anagram