Skip navigation
leetcode 242: valid anagram 🔤
0:00

leetcode 242: valid anagram 🔤

#leetcode #techinterview #algorithms

leetcode 242: valid anagram 🔤 it looks like a one-liner, and that’s the trap 👀 amazon and google both ask it, and most people sort both strings and stop there. ✅ listen / silent → true (every letter shows up exactly once in both) ❌ rat / car → false (car has a c, rat doesn’t) ❌ ac / bb → false, even though a + c and b + b both add up to 4 ❌ aab / abb → false, same letters but different amounts sorting works, but it costs o(n log n) time. the fix? count every letter 🧠 keep 26 counters, one for each lowercase letter, and find a letter’s slot with ord(c) - ord(‘a’). walk through s and add one for every letter, then walk through t and subtract one. if t uses exactly the same letters, every plus gets cancelled by a minus and every counter ends at zero. one counter off zero means it’s not an anagram. o(n) time, o(1) space, because the array always has 26 slots 🔥 the same counting idea is the key to group anagrams and find all anagrams in a string. 💾 save this for your next string review 💬 did you reach for sorting or counting first? 👉 follow for a new interview problem every couple of days #leetcode #techinterview #algorithms #coding #learntocode

Comments

Comments from the original post on Instagram

No comments yet