Given two strings s and t, determine if t is an anagram of s.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
You may assume the strings contain only lowercase English letters.
-
Constraints:
1 <= s.length, t.length <= 5 * 10^4sandtconsist of lowercase English letters.
-
Example 1:
Input: s = "anagram", t = "nagaram" Output: true -
Example 2:
Input: s = "rat", t = "car" Output: false
Solution
A common approach to check for anagrams is to use character frequency counting.
- Check Lengths First: If
sandthave different lengths, they cannot be anagrams. Returnfalseimmediately. - Frequency Array: Initialize an array (or hash map) of size 26 (for lowercase English letters) to store character counts, initialized to zero.
- Count
sCharacters: Iterate through strings. For each character, increment its corresponding count in the frequency array. - Decrement
tCharacters: Iterate through stringt. For each character:- Decrement its corresponding count in the frequency array.
- If the count for any character drops below zero, it means
thas more occurrences of that character thans(orsdoesn't have it at all). In this case, they cannot be anagrams. Returnfalse.
- Final Check: If the loop finishes without returning
false, it implies that every character intwas matched by a character ins, and because the initial lengths were equal, all counts in the frequency array must have returned to zero. Thus,sandtare anagrams. Returntrue.
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
# Initialize a frequency array for 26 lowercase English letters
char_counts = [0] * 26
# Count character frequencies in string s
for char_s in s:
char_counts[ord(char_s) - ord('a')] += 1
# Decrement character frequencies for string t
for char_t in t:
char_counts[ord(char_t) - ord('a')] -= 1
# If a count drops below zero, t has an extra character or a different character
if char_counts[ord(char_t) - ord('a')] < 0:
return False
# If all characters in t were successfully decremented (without any count going negative),
# and initial lengths were equal, then all counts must be zero.
return True