Valid Anagram
Valid Anagram
Section titled “Valid Anagram”
Easy
Day 11 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”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.
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
s = "anagram", t = "nagaram" - Output:
true
Example 2:
- Input:
s = "rat", t = "car" - Output:
false
Constraints:
1 ≤ s.length, t.length ≤ 5 × 10⁴s and t consist of lowercase English letters
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”Valid Anagram tests your ability to compare character frequencies efficiently using a hash map or fixed-size counting array.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Pattern: Frequency Counting
When comparing whether two collections contain the same elements (ignoring order), count occurrences of each element and compare the counts.
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD Start["Input Data"] --> Process["Process Element by Element"] Process --> Lookup{"Hash Map / Set Lookup"} Lookup -- "Match Found" --> Return["Return Indices / Result"] Lookup -- "No Match" --> Store["Store in Map / Set"] Store --> Process🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”function isAnagram(s, t) { return s.split('').sort().join('') === t.split('').sort().join('');}- Time Complexity:
O(n log n) - Space Complexity:
O(n) - Explanation: Sort both strings and compare.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function isAnagram(s, t) { if (s.length !== t.length) return false; const counts = new Map(); for (const c of s) counts.set(c, (counts.get(c) || 0) + 1); for (const c of t) { if (!counts.get(c)) return false; counts.set(c, counts.get(c) - 1); } return true;}- Time Complexity:
O(n) - Space Complexity:
O(1) - Explanation: Count characters in one pass, decrement in the other.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”How to explain:
- Start with sorting-based comparison
- Point out sorting costs O(n log n)
- Move to frequency counting with a hash map for O(n)
- Early exit on length mismatch
💡 Progressive Hints
Section titled “💡 Progressive Hints”- If the lengths differ, they can’t be anagrams.
- Count the frequency of each character in both strings.
- A hash map or a 26-element array works well for lowercase letters.