The Challenge: 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.)
π‘ The "Aha!" Moment
I initially thought about just checking if every letter in s existed in t. But I realized that fails for words with duplicate letters (like "Apple" vs "Pale"). Just knowing a letter exists isn't enough; I needed to know how many times it appears. I needed a full inventory, not just a guest list.
π οΈ My Strategy: The "Inventory Check"
- Data Structure: I used two Hash Maps (Dictionaries) to store character counts.
- Mechanism: I treated the dictionaries like inventory receipts.
- Logic:
- Fail Fast: If the strings have different lengths, they can't be anagrams. Return
False. - Count: Loop through each string and count how many times each letter appears.
- Compare: Check if the "inventory receipt" for
sis identical tot.
- Fail Fast: If the strings have different lengths, they can't be anagrams. Return
π Python Implementation
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# 1. Fail Fast: Different lengths? Not anagrams.
if len(s) != len(t):
return False
# create dictionary to store count
countS = {}
countT = {}
# search
for letter in s:
if letter in countS:
countS[letter] += 1
else:
countS[letter] = 1
for letter in t:
if letter in countT:
countT[letter] += 1
else:
countT[letter] = 1
# Check if the dictionaries are identical
return countS == countT
π Performance Reflection
Time Complexity:
Space Complexity:
β Proof of Acceptance :