Valid Anagram
π NeetCode Problem:https://neetcode.io/problems/is-anagram/question?list=neetcode150 π LeetCode Problem:
https://leetcode.com/problems/valid-anagram/
Problem Statement
Given two stringss and t, return true if t is an anagram of s, and return false otherwise.
An anagram is a word formed by rearranging the letters of another word, using all the original letters exactly once.
Approach 1: Sorting (Simple but Not Optimal)
Idea
Sort both strings and compare them. If theyβre equal after sorting, theyβre anagrams.Pseudocode
- Sort string
s - Sort string
t - Compare if sorted strings are equal
Time Complexity
- O(n log n) β Due to sorting
Why itβs not optimal?
Sorting takes extra time. For anagrams, we only need to count characters, not arrange them.Optimized Approach 1: Using Hash Map (Unordered Map)
Idea
Count the frequency of each character in both strings using hash maps.If the frequency maps are identical, the strings are anagrams.
Key Insight
We can compare character frequencies without rearranging.C++ Implementation
Complexity Analysis
- Time Complexity: O(n) β Single pass through each string
- Space Complexity: O(1) β Max 26 characters (lowercase English letters)
Optimized Approach 2: Using Frequency Array (Most Optimal)
Idea
Use a fixed-size array of 26 (for lowercase English letters) to count frequencies.Increment for characters in
s, decrement for characters in t.If any count goes negative, theyβre not anagrams.
Key Insight
Since we only have 26 possible lowercase letters, an array is more efficient than a hash map.C++ Implementation
Complexity Analysis
- Time Complexity: O(n) β Two passes through the strings
- Space Complexity: O(1) β Fixed array of 26 elements
Comparison of Approaches
| Approach | Time Complexity | Space Complexity | Pros | Cons |
|---|---|---|---|---|
| Sorting | O(n log n) | O(1) | Simple | Slower |
| Hash Map | O(n) | O(1)* | Flexible for any characters | More memory per hash |
| Frequency Array | O(n) | O(1) | Most efficient | Limited to 26 letters |
Why Frequency Array is Most Optimal
- Fixed size: Only 26 possible letters
- No hashing overhead: Direct array indexing is faster
- Early termination: Can return false immediately if count goes negative
- Minimal memory: Array of 26 integers vs hash map overhead
Example Walkthrough
Example 1: s = "listen", t = "silent"
Using Frequency Array:
Example 2: s = "hello", t = "world"
s, so it goes negative β Not an anagram!
Key Takeaways
- Avoid sorting for this problem (O(n log n) is slower than needed)
- Frequency array is optimal (O(n) time, O(1) space)
- Character counting approach: Count occurrences, donβt rearrange
- Two-pass is efficient: Simple increment/decrement operations
- Early termination: Return false immediately if a character doesnβt match
- Fixed alphabet: For English letters, array is faster than hash map