Valid Anagram
🎯 Difficulty: EASY
🔗 LeetCodeProblem Statement
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.
Example:
Input: s = “anagram”, t = “nagaram”
Output: true
Approach: Hash Map / Frequency Counter
The most efficient way to solve this is to count the occurrences of each character. Since the problem typically limits the characters to lowercase English letters, we can use an array of size 26 or a standard JavaScript object/Hash Map to track frequencies.
- First, check if the lengths of
sandtare different. If they are, they cannot be anagrams, so returnfalse. - Initialize a frequency map (or an object) to store character counts.
- Iterate through both strings simultaneously. Increment the count for the character from
sand decrement the count for the character fromt. - Finally, iterate through the frequency map. If any character count is not exactly
0, it means the strings have different characters or quantities. Returnfalse. - If all counts are
0, returntrue.
Solution
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const count = {};
for (let i = 0; i < s.length; i++) {
count[s[i]] = (count[s[i]] || 0) + 1;
count[t[i]] = (count[t[i]] || 0) - 1;
}
for (let char in count) {
if (count[char] !== 0) {
return false;
}
}
return true;
}
Complexity Analysis
- Time Complexity: where is the length of the strings. We iterate through the strings once, which takes time. The final loop through the hash map takes time because there are at most 26 unique characters.
- Space Complexity: . The size of the hash map is bounded by the number of unique characters in the alphabet (e.g., 26 lowercase English letters), so it requires constant extra space regardless of the input size.