Valid Anagram Problem Solution

🚀 Day 10/30– DSA Challenge 📌 LeetCode Problem – Valid Anagram 📝 Problem Statement Given two strings s and t, determine whether t is an anagram of s. A string is an anagram if it contains the same characters with the same frequency, but possibly in a different order. 📌 Example Input: s = "anagram" t = "nagaram" Output: true Explanation: Both strings contain the same characters with the same counts. Another Example Input: s = "rat" t = "car" Output: false Explanation: Characters are different. 💡 Initial Thought Process Brute force idea: Sort both strings Compare them If they are equal → anagram. Time Complexity: O(n log n) because of sorting. But we can do better. 🔥 Optimized Approach – Frequency Count 🧠 Key Insight Since strings contain lowercase English letters, we can store character frequencies using an array of size 26. Steps: Count frequency of characters in s Decrease frequency using characters in t If any value becomes negative → not an anagram 🚀 Algorithm 1️⃣ If lengths differ → return false 2️⃣ Create array count[26] 3️⃣ Traverse string s count[s[i] - 'a']++ 4️⃣ Traverse string t count[t[i] - 'a']-- 5️⃣ If any count < 0 → return false 6️⃣ Otherwise → return true ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) (fixed array of 26) 📚 Key Learnings – Day 10 ✔ Frequency counting is powerful for string problems ✔ Avoid sorting when counting works ✔ Hashing / frequency arrays appear often in interviews ✔ Think about character constraints Two strings. Simple logic. Efficient solution. Day 10 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Strings #LeetCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories