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^4
    • s and t consist 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 s and t have different lengths, they cannot be anagrams. Return false immediately.
  • Frequency Array: Initialize an array (or hash map) of size 26 (for lowercase English letters) to store character counts, initialized to zero.
  • Count s Characters: Iterate through string s. For each character, increment its corresponding count in the frequency array.
  • Decrement t Characters: Iterate through string t. For each character:
    • Decrement its corresponding count in the frequency array.
    • If the count for any character drops below zero, it means t has more occurrences of that character than s (or s doesn't have it at all). In this case, they cannot be anagrams. Return false.
  • Final Check: If the loop finishes without returning false, it implies that every character in t was matched by a character in s, and because the initial lengths were equal, all counts in the frequency array must have returned to zero. Thus, s and t are anagrams. Return true.
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