Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise. 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.
- 1 <= s.length, t.length <= 5 ร 10โด
- s and t consist of lowercase English letters
s = "anagram", t = "nagaram"trues = "rat", t = "car"falses = "a", t = "ab"falseChecking if two words are anagrams means verifying they contain the exact same characters in the exact same quantities, just arranged differently. The goal is to determine if one string is simply a scrambled version of the other.
If we sort the characters in both strings, two anagrams will become identical. We can then compare the sorted results directly to see if the "ingredients" match.
if len(s) != len(t): return False
return sorted(s) == sorted(t)The sorting approach is slow because it rearranges data when we only need to compare frequencies. The core insight is that an anagram is just a character inventory. If we count how many times each letter appears in both strings, the inventories must match perfectly.
We use a fixed-size array (26 for lowercase English) to track the balance of characters.
- For every character in s, we increment its slot in the array.
- For every character in t, we decrement its slot.
If all slots end at zero, the strings are anagrams.
if len(s) != len(t): return False
counts = [0] * 26
for i in range(len(s)):
counts[ord(s[i]) - ord('a')] += 1
counts[ord(t[i]) - ord('a')] -= 1
return all(x == 0 for x in counts)Bucket Balancing
Processing input string. For every A, we increment the count.