Valid Anagram
Difficulty: Easy
Given two strings, return true if the second is an anagram of the first, and false otherwise. An anagram uses exactly the same letters the same number of times, possibly in a different order.
Examples
Input: s = "anagram", t = "nagaram"
Output: true
Both strings contain the same seven letters with the same counts, just rearranged.
Input: s = "rat", t = "car"
Output: false
The letters don't match - "car" has a c, and "rat" doesn't.
Input: s = "a", t = "ab"
Output: false
Different lengths can never be anagrams of each other.
Constraints
1 <= s.length, t.length <= 5 * 10^4
s and t consist of lowercase English letters.
Approach
Two strings are anagrams when they contain the same letters the same number of times. One simple check: sort both strings alphabetically. If they're anagrams, the sorted versions are identical.
A faster way skips sorting. Count each letter in the first string, then walk the second string subtracting from those counts. If every count ends at exactly zero, the strings are anagrams.
Solutions
Brute Force - Sort and Compare
Anagrams produce the same string when their letters are sorted. So sort both strings and compare.
function isAnagram(s, t) {
if (s.length !== t.length) {
return false;
}
const sSorted = s.split("").sort().join("");
const tSorted = t.split("").sort().join("");
return sSorted === tSorted;
}Time: O(n log n) · Space: O(n)
Optimal - Character Count
Count each letter in s with a hash map. Then scan t, decreasing the count for each letter. If t needs a letter that isn't available, the strings aren't anagrams.
function isAnagram(s, t) {
if (s.length !== t.length) {
return false;
}
const counts = new Map();
for (const ch of s) {
counts.set(ch, (counts.get(ch) || 0) + 1);
}
for (const ch of t) {
if (!counts.has(ch) || counts.get(ch) === 0) {
return false;
}
counts.set(ch, counts.get(ch) - 1);
}
return true;
}Time: O(n) · Space: O(1) - at most 26 lowercase letters, so the map's size is bounded by a constant