Valid Anagram Solution on LeetCode

🚀 𝗗𝗮𝘆 12 𝗼𝗳 𝗖𝗼𝗻𝘀𝗶𝘀𝘁𝗲𝗻𝗰𝘆 — Solved “Valid Anagram” on LeetCode Today I worked on a classic string problem: Valid Anagram — a great question to strengthen understanding of frequency counting and optimized string handling. 🔍 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 Given two strings s and t, determine whether t is an anagram of s. 👉 Anagram means both strings contain the same characters with the same frequency. 🧠 𝗕𝗿𝘂𝘁𝗲 𝗙𝗼𝗿𝗰𝗲 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 Sort both strings Compare them ⏱ Time Complexity: O(n log n) 👉 Works fine but not optimal for interviews ⚡ 𝗢𝗽𝘁𝗶𝗺𝗶𝘇𝗲𝗱 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 (Used Today) Instead of sorting, I used frequency counting with arrays. ✅ 𝗦𝘁𝗲𝗽𝘀: If lengths are different → return false Create two arrays of size 26 (for lowercase letters) Count frequency of characters in both strings Compare both frequency arrays 💻 𝗖𝗼𝗱𝗲 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 Increment count for characters in s Increment count for characters in t Compare both arrays → if all values match → anagram ✅ 📌 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 s = "anagram" t = "nagaram" ✔ Same frequency → Valid Anagram ⏱ 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀 Time: O(n) Space: O(1) (constant size array) 💡 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 Always try to replace sorting with counting when dealing with characters Frequency array is a powerful optimization technique Writing clean and optimal code improves both performance and interview confidence Grateful for continuous learning and growth 🙏 Consistency is the real game changer 💯 #LeetCode #DSA #Java #ProblemSolving #CodingJourney #100DaysOfCode #TechLearning #SoftwareDevelopment

  • text

To view or add a comment, sign in

Explore content categories