Two strings are anagrams when they use the exact same letters with the exact same multiplicities. Skip sorting — a single frequency count (one pass up for s, one pass down for t) decides it in linear time.
Return true if t is an anagram of s — same letters, same counts, any order. s="anagram", t="nagaram" → true. s="rat", t="car" → false.
s, then "spend" it down with t— if you ever overspend or finish with leftovers, they're not anagrams.s. For each char, count[c]++.t. For each char, count[c]--. If it ever goes below zero, t has a letter s lacks → false.true.If restricted to lowercase a–z, a fixed number[26] array gives O(1) space. For full Unicode, a Map is O(k) where k = distinct characters. The sorting approach is the easiest to say but the count is the one to code.
7). Phase 1: tally every letter of s.function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) return false;
const count = new Map<string, number>();
for (const c of s) { // tally s: +1
count.set(c, (count.get(c) ?? 0) + 1);
}
for (const c of t) { // drain with t: -1
const n = (count.get(c) ?? 0) - 1;
if (n < 0) return false; // t has a char s lacks
count.set(c, n);
}
return true; // equal lengths + never negative => all zero
}s. The ?? 0 handles first-time keys.t decrements its count. Going negative means t uses a letter more often than s has it → not an anagram.number[26]).Map instead of a 26-slot array; or normalize first.| "same letters, any order" | frequency count map |
| compare two strings' makeup | +1 for one, −1 for other |
| fixed lowercase alphabet | number[26] → O(1) space |
| "group / find all anagrams" | count signature as a key |
if (s.length !== t.length) return false;
const count = new Map<string, number>();
for (const c of s) count.set(c, (count.get(c) ?? 0) + 1);
for (const c of t) {
const n = (count.get(c) ?? 0) - 1;
if (n < 0) return false;
count.set(c, n);
}
return true;