Valid Anagram
Watch the walkthrough
Open on InstagramProblem
Decide whether two strings contain the same characters with the same multiplicities.
Approach and revision checks
Reject unequal lengths, count the first string, then decrement for the second and fail on a missing character. O(n+m) time and O(k) extra space for k distinct characters. For a fixed alphabet, k is bounded. The source processes UTF-16 code units without case folding or normalization. Example: anagram/nagaram -> true; rat/car -> false.
Original repository source
Copied from the supplied local DSA-Series checkout; code and comments are preserved. Run alternative definitions separately when comparing approaches.
10-valid-anagram.js
// TC: O(N+M) Sc: O(N)
var isAnagram = function (s, t) {
if (s.length !== t.length) return false;
const charCount = {};
for (let i = 0; i < s.length; i++) {
charCount[s[i]] = (charCount[s[i]] || 0) + 1;
}
for (let i = 0; i < t.length; i++) {
if (!charCount[t[i]]) {
return false;
}
charCount[t[i]]--;
}
return true;
};