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 another, using all the original letters exactly once.
Example:
Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false
obj) to store the frequency of characters in s.t while traversing.t doesn’t exist in obj or the frequencies don’t balance to 0, return false.0.
function isAnagram(s, t) {
if (s.length !== t.length) return false;
let obj = {};
// Count frequencies of characters in `s`
for (let i = 0; i < s.length; i++) {
obj[s[i]] = (obj[s[i]] || 0) + 1;
}
// Decrease frequencies based on characters in `t`
for (let i = 0; i < t.length; i++) {
if (!obj[t[i]]) return false; // Character not found or excess in `t`
obj[t[i]]--;
}
// Ensure all frequencies are balanced
for (let key in obj) {
if (obj[key] !== 0) return false;
}
return true;
}
O(N)
O(N)
s and decrement for characters in t.0.