🔗 Problem Link
LeetCode 242 – Valid Anagram
👉 https://leetcode.com/problems/valid-anagram/
Introduction
This is one of the most important string frequency problems in coding interviews.
The idea of checking whether two strings are anagrams appears in many variations:
- Group Anagrams
- Ransom Note
- Find the Difference
- Permutation in String
If you master this pattern, you unlock a whole category of problems.
Let’s break it down step by step.
📌 Problem Understanding
Two strings are anagrams if:
- They contain the same characters
- With the same frequencies
- Order does not matter
Example 1
Both contain:
Example 2
Different character frequencies.
🧠 Intuition
The core idea:
If two strings are anagrams, their character frequencies must match exactly.
So we:
- Check if lengths are equal.
- Count frequency of characters in first string.
- Subtract frequencies using second string.
- If at any point frequency becomes negative → not anagram.
💻 Your Code
🔍 Step-by-Step Explanation
1️⃣ Length Check
If lengths differ → cannot be anagrams.
2️⃣ Build Frequency Map
Count occurrences of each character in s.
3️⃣ Subtract Using Second String
If character exists and frequency is available → reduce it.
Otherwise → return false immediately.
🎯 Why This Works
We treat:
- First string as frequency builder
- Second string as frequency consumer
If all frequencies match perfectly, we return true.
⏱ Complexity Analysis
Time Complexity: O(n)
- One pass to build map
- One pass to compare
Space Complexity: O(26) ≈ O(1)
Only lowercase English letters allowed.
🔥 Optimized Approach – Using Array Instead of HashMap
Since the problem guarantees:
We can replace HashMap with an integer array of size 26.
This is faster and cleaner.
Optimized Version
🚀 Why This Is Better
- No HashMap overhead
- Direct index access
- Cleaner code
- Faster in interviews
🏁 Final Thoughts
This problem teaches:
- Frequency counting pattern
- Early exit optimization
- Using arrays instead of HashMap when character set is limited
- Thinking in terms of resource balance
Valid Anagram is a foundation problem.
Once you master it, you can easily solve:
- Ransom Note
- Find the Difference
- Group Anagrams
- Check Equal Character Occurrences




