Farhan, a final-year BCA student in Dehradun, is in a mock interview over a video call. The question sounds easy: "Write a function that tells me whether listen and silent are anagrams." He writes two nested loops: for each letter of the first word, look for it in the second word. It prints true, and he relaxes. Then the interviewer types isAnagram("aab", "abb"). That also prints true, even though one word has two a's and the other has two b's. "Why does your code think these match," she asks, "and can you do it without a loop inside a loop?" So what is the correct way to check two strings for anagrams, and how do you do it quickly?
That is the question this post answers. The anagram problem shows up on LeetCode, HackerRank and in almost every list of JavaScript interview questions, because it tests several skills in one short function: string handling, counting with an object or a Map, and reasoning about time complexity. We will cover the sorting approach, the faster frequency-count approach, how to decide what counts as a "letter", a Unicode trap that breaks many textbook answers, and the popular follow-up of grouping anagrams. Every code sample was run on Node.js v24, and the comments show the real output.
What Is an Anagram?
Two strings are anagrams when one can be made by rearranging the characters of the other, using every character exactly as many times as it appears. Order does not matter, but the count of each character does. listen and silent are anagrams. So are hello and ollhe, because both contain one h, one e, two l's and one o:
const count = {};
for (const ch of "hello") count[ch] = (count[ch] || 0) + 1;
console.log(count); // { h: 1, e: 1, l: 2, o: 1 }
Think of five letter tiles in a box, H E L L O. Shuffle them into O L L H E and the box still holds exactly the same tiles. That picture gives us the two rules every solution must check: both strings must have the same length, and each character must appear the same number of times in both. hello and heloo fail the second rule even though they use the same set of letters, because one has two l's and the other has two o's.
Step 0: The Early Length Check
If the lengths differ, the strings cannot be anagrams, so every solution below starts with this line:
if (a.length !== b.length) return false;
It costs almost nothing, because a string's length is stored and does not need a loop. It rejects pairs like hello and helloo before any counting or sorting starts. It also makes the counting solution simpler: once we know the lengths are equal, we never need a final loop to check that every count went back to zero (the trace further down shows why). One caution: if you clean the strings first (lower-casing, removing spaces), do the length check after cleaning, or "rail safety" and "fairy tales!" will be rejected for the wrong reason.
Why the Nested-Loop Answer Is Wrong
An earlier version of this post showed the same brute-force idea Farhan used. It is a natural first attempt, so it is worth seeing exactly where it breaks:
function bruteIsAnagram(str1, str2) {
if (str1.length !== str2.length) return false;
for (let i = 0; i < str1.length; i++) {
let found = false;
for (let j = 0; j < str2.length; j++) {
if (str1[i] === str2[j]) {
found = true;
break;
}
}
if (!found) return false;
}
return true;
}
console.log(bruteIsAnagram("aab", "abb")); // true (wrong!)
console.log(bruteIsAnagram("hello", "heloo")); // true (wrong!)
The code only asks "does this letter exist somewhere in the other string?" It never uses a letter up, so the single a in abb is found twice. To make it correct, remove each matched character so it cannot be matched again:
function isAnagramBrute(a, b) {
if (a.length !== b.length) return false;
const rest = b.split("");
for (const ch of a) {
const i = rest.indexOf(ch);
if (i === -1) return false;
rest.splice(i, 1); // use this character up
}
return true;
}
console.log(isAnagramBrute("aab", "abb")); // false
console.log(isAnagramBrute("listen", "silent")); // true
This version is correct for plain English words, but it is slow. indexOf and splice both walk through the array, and they run once for every character, so the total work is O(n²). For two strings of 1,000 characters that is on the order of a million steps. The next two approaches do much better.
Approach 1: Sort and Compare (O(n log n))
If two strings are anagrams, sorting their characters produces the same result. listen and silent both sort to eilnst. That gives a very short solution:
function isAnagramSort(a, b) {
if (a.length !== b.length) return false;
const sortChars = (s) => s.split("").sort().join("");
return sortChars(a) === sortChars(b);
}
console.log(isAnagramSort("listen", "silent")); // true
console.log(isAnagramSort("hello", "heloo")); // false
console.log("listen".split("").sort().join("")); // eilnst
Sorting takes O(n log n) time, and building the arrays takes O(n) extra memory. For interview-sized input that is perfectly fine, and the code is easy to read. The original post called this a mistake if you use it "without understanding". It is better described as a valid answer that you should be able to explain, and then improve on if the interviewer asks for O(n). There is also a hidden problem in split(""), which the Unicode section below covers.
Approach 2: Frequency Count with an Object (O(n))
The faster approach is the frequency counter pattern: instead of searching or sorting, count how many times each character appears. Count up for the first string, then count down for the second. If any count would go below zero, the strings are not anagrams.
function isAnagram(a, b) {
if (a.length !== b.length) return false;
const count = {};
for (const ch of a) count[ch] = (count[ch] || 0) + 1;
for (const ch of b) {
if (!count[ch]) return false; // missing, or already used up
count[ch]--;
}
return true;
}
console.log(isAnagram("listen", "silent")); // true
console.log(isAnagram("hello", "heloo")); // false
console.log(isAnagram("aab", "abb")); // false
console.log(isAnagram("Listen", "silent")); // false (L and l are different)
The expression (count[ch] || 0) + 1 reads "the current count, or 0 if this character has not been seen yet, plus one". In the second loop, !count[ch] is true both when the character never appeared (the value is undefined) and when it has been used up (the value is 0). The original post's sol() function used exactly this logic, and it is correct.
Each string is read once, so the time is O(n). The extra memory is O(k), where k is the number of different characters, not the length of the string. For lowercase English words k can never be more than 26, however long the strings are.
Trace: "listen" and "silent"
Here is the count object after each step. The first loop builds the table from listen; the second loop takes one away for each letter of silent:
| Step | Character | Action | Count table after the step |
|---|---|---|---|
| 1 | l | add | { l: 1 } |
| 2 | i | add | { l: 1, i: 1 } |
| 3 | s | add | { l: 1, i: 1, s: 1 } |
| 4 | t | add | { l: 1, i: 1, s: 1, t: 1 } |
| 5 | e | add | { l: 1, i: 1, s: 1, t: 1, e: 1 } |
| 6 | n | add | { l: 1, i: 1, s: 1, t: 1, e: 1, n: 1 } |
| 7 | s | 1 → 0 | { l: 1, i: 1, s: 0, t: 1, e: 1, n: 1 } |
| 8 | i | 1 → 0 | { l: 1, i: 0, s: 0, t: 1, e: 1, n: 1 } |
| 9 | l | 1 → 0 | { l: 0, i: 0, s: 0, t: 1, e: 1, n: 1 } |
| 10 | e | 1 → 0 | { l: 0, i: 0, s: 0, t: 1, e: 0, n: 1 } |
| 11 | n | 1 → 0 | { l: 0, i: 0, s: 0, t: 1, e: 0, n: 0 } |
| 12 | t | 1 → 0 | { l: 0, i: 0, s: 0, t: 0, e: 0, n: 0 } |
No step found a missing or used-up letter, so the function returns true. Now compare hello and heloo. The table starts as { h: 1, e: 1, l: 2, o: 1 }. After h, e, l and the first o, the o count is 0, so the second o hits !count["o"] and the function returns false right there.
Why is there no final check that every count is zero? Because the lengths are equal. If every one of the n characters of the second string successfully took one away, then exactly n units were removed from a table holding n units, so nothing can be left over. Drop the length check and this shortcut stops being safe: isAnagram("aab", "ab") would then return true.
The Same Thing with a Map
A Map does the same job and is often the cleaner choice. Its keys never clash with built-in object properties, and its methods (get, set, has) make the intent obvious:
function isAnagramMap(a, b) {
if (a.length !== b.length) return false;
const count = new Map();
for (const ch of a) count.set(ch, (count.get(ch) || 0) + 1);
for (const ch of b) {
const n = count.get(ch);
if (!n) return false;
count.set(ch, n - 1);
}
return true;
}
console.log(isAnagramMap("listen", "silent")); // true
console.log(isAnagramMap("rat", "car")); // false
For single characters, a plain object is safe, because no built-in property such as constructor has a one-character name. When the keys are whole words (as in the group-anagrams problem later), a plain {} already "contains" keys like constructor through its prototype, which can cause confusing bugs. That is a good habit-forming reason to reach for Map when counting.
Decide the Rules: Case, Spaces and Punctuation
Is Listen an anagram of silent? Is Dormitory an anagram of Dirty room!? There is no single right answer; it depends on the requirement. A good function makes its rules explicit instead of leaving them to chance. The original post's "production-ready" version used this cleaning step:
str1 = str1.toLowerCase().replace(/[^a-z0-9]/g, "");
It works for English phrases, but it has two quiet problems. It deletes every letter outside a to z, so accented letters and whole scripts like Hindi disappear. And when both strings clean down to nothing, the function returns true:
console.log(origIsAnagram("Dormitory", "Dirty room!")); // true
console.log(origIsAnagram("नमस्ते", "!!!")); // true (both become "")
console.log(origIsAnagram("", "")); // true
Here is a version that states its rules in one place. It ignores case, spaces and punctuation, keeps letters and digits from any language, and refuses to call two empty strings anagrams. The u flag turns on Unicode mode in the regular expression, so \p{L} means "any letter", \p{M} means "any combining mark" (needed for Hindi vowel signs) and \p{N} means "any digit".
// Rules: ignore case, spaces and punctuation; keep letters and digits
// from any script; two empty strings are NOT anagrams.
function normalise(s) {
return s
.normalize("NFC")
.toLowerCase()
.replace(/[^\p{L}\p{M}\p{N}]/gu, "");
}
function isPhraseAnagram(a, b) {
const x = normalise(a);
const y = normalise(b);
if (x.length === 0 || x.length !== y.length) return false;
const count = new Map();
for (const ch of x) count.set(ch, (count.get(ch) || 0) + 1);
for (const ch of y) {
const n = count.get(ch);
if (!n) return false;
count.set(ch, n - 1);
}
return true;
}
console.log(isPhraseAnagram("Dormitory", "Dirty room!")); // true
console.log(isPhraseAnagram("Rail safety", "fairy tales")); // true
console.log(isPhraseAnagram("Astronomer", "Moon starer")); // true
console.log(isPhraseAnagram("Hello", "hello")); // true
console.log(isPhraseAnagram("नमस्ते", "!!!")); // false
console.log(isPhraseAnagram("नमस्ते", "तेनमस्")); // true
console.log(isPhraseAnagram("", "")); // false
Notice that the rules are written as a comment at the top. If your requirement is different (say, case matters for passwords, or digits should be ignored), you change one function, and everyone reading the code can see what "anagram" means in your project. The normalize("NFC") call is explained next.
The Unicode Gotcha: split("") Breaks Emoji and Accents
JavaScript strings are stored as UTF-16 code units. Most common characters take one code unit, but emoji and many rarer characters take two (called a surrogate pair). split("") and str.length work on code units, while for...of, the spread syntax [...str] and Array.from(str) work on whole code points:
const s = "a😀b";
console.log(s.length); // 4
console.log(s.split("")); // [ 'a', '\ud83d', '\ude00', 'b' ]
console.log([...s]); // [ 'a', '😀', 'b' ]
console.log(Array.from(s)); // [ 'a', '😀', 'b' ]
So the sort-and-compare solution cuts emoji in half before sorting. You can see the damage when you print the sorted string, and you can even build two different emoji pairs that it wrongly calls anagrams, because their halves happen to match:
console.log("😀🌍".split("").sort().join("")); // �😀� (halves shuffled)
console.log([..."😀🌍"].sort().join("")); // 🌍😀
const a = "😀🌍";
const b = "🜍🈀"; // two different symbols made from the same four halves
console.log(isAnagramSort(a, b)); // true (wrong)
function isAnagramSortSafe(a, b) {
if (a.length !== b.length) return false;
const sortChars = (s) => [...s].sort().join("");
return sortChars(a) === sortChars(b);
}
console.log(isAnagramSortSafe(a, b)); // false
console.log(isAnagramSortSafe("🍕🍔", "🍔🍕")); // true
The frequency-count solutions above already use for...of, so they count whole code points and do not have this bug. Their length check still uses code units, which is fine: two strings with the same code points always have the same code-unit length.
One "é", Two Spellings
Accented letters bring a second trap. The letter "é" can be stored as one code point (U+00E9) or as a plain "e" followed by a combining accent (U+0301). Both look identical on screen, but JavaScript sees different strings. normalize("NFC") converts both to the same composed form:
const a = "é"; // é as one code point
const b = "é"; // e + combining accent
console.log(a === b); // false
console.log(a.length, b.length); // 1 2
console.log(a.normalize("NFC") === b.normalize("NFC")); // true
isAnagram in a small word game for his college fest, where players find anagrams of their own names. A friend named Zoë types her name on her phone, and the game gets "ë" as one code point. The same name pasted from a laptop document arrives as "e" plus a combining mark. isAnagram("Zoë", "ëZo") returns false, because one string has length 3 and the other has length 4. Adding .normalize("NFC") to both inputs makes it return true. This is exactly why normalise() above calls normalize("NFC") before anything else.Even [...str] has a limit. Some characters that look like one symbol are built from several code points, such as the family emoji 👨👩👧, which has a length of 8 and spreads into 5 code points. To treat it as one visible character you need Intl.Segmenter with granularity: "grapheme". For interview answers, code points plus NFC are enough; just mention that graphemes exist if the interviewer asks about emoji.
Comparing the Approaches
| Approach | Time | Extra memory | Unicode-safe? | When to use it |
|---|---|---|---|---|
| Nested loops (original) | O(n²) | O(1) | No | Never: it ignores counts, so "aab"/"abb" gives true |
Nested loops with splice | O(n²) | O(n) | No (uses split("")) | Only to explain the idea |
Sort with split("") | O(n log n) | O(n) | No, breaks emoji | Quick answers on plain ASCII text |
Sort with [...str] | O(n log n) | O(n) | Code points, yes | Short, readable code; group-anagram keys |
| Frequency count (object) | O(n) | O(k) distinct characters | Code points, yes | The standard interview answer |
Frequency count (Map) | O(n) | O(k) | Code points, yes | Same, with cleaner keys; best default |
Big-O hides constants, so for short words the sort version can be just as fast in practice. The difference matters for long strings, or when you call the check many thousands of times.
Follow-Up: Group Anagrams
Once you solve the two-string version, the next interview question is often: "Given a list of words, group the anagrams together." For ["eat", "tea", "tan", "ate", "nat", "bat"] the answer is three groups. The trick is to give every word a key that is the same for all its anagrams, such as its sorted letters, and collect words in a Map by that key:
function groupAnagrams(words) {
const groups = new Map();
for (const word of words) {
const key = [...word].sort().join(""); // "eat", "tea", "ate" → "aet"
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(word);
}
return [...groups.values()];
}
console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));
// [ [ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ] ]
console.log(groupAnagrams([])); // []
console.log(groupAnagrams([""])); // [ [ '' ] ]
A Map remembers insertion order, so the groups come out in the order their first word appeared. For n words of up to m letters, this takes O(n × m log m) time. If the words are only lowercase a to z, you can replace sorting with a count of 26 letters and make it O(n × m):
function groupAnagramsCount(words) { // lowercase a-z only
const groups = new Map();
for (const word of words) {
const counts = new Array(26).fill(0);
for (const ch of word) counts[ch.charCodeAt(0) - 97]++; // 'a' is 97
const key = counts.join(",");
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(word);
}
return [...groups.values()];
}
console.log(groupAnagramsCount(["eat", "tea", "tan", "ate", "nat", "bat"]));
// [ [ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ] ]
The comma in counts.join(",") is not decoration. Without it, counts of [1, 11] and [11, 1] would both become the key "111" and two different words would land in the same group. With the comma they become "1,11" and "11,1". This version also assumes clean input: an uppercase letter or a space would produce an index outside 0 to 25, so normalise first or use the sorted-key version.
Where the Frequency Counter Pattern Shows Up Again
The word "anagram" matters less than the pattern behind it. Counting things in an object or Map instead of searching repeatedly solves many other problems: finding the first non-repeating character, checking whether one array contains the squares of another, spotting duplicates, counting word frequency in a review, or checking whether a ransom note can be built from a magazine's letters. Word games such as Scrabble helpers use the same counting idea to check which words can be made from a rack of tiles. When you meet a problem that asks "same items, any order?", reach for a count table first.
Interviewers often care as much about how you explain this as about the code. A good answer sounds like: "First I'll check the lengths. Then I'll count each character of the first string in a Map and count down with the second. That's O(n) time and O(k) space. I'm assuming case matters and spaces count; tell me if you'd like those ignored."
Common Mistakes (and the Fix)
| Mistake | What happens | Fix |
|---|---|---|
| Only checking that each letter exists in the other string | "aab" and "abb" are reported as anagrams | Count frequencies, or remove each matched character |
| Skipping the length check in the count-down solution | isAnagram("aab", "ab") returns true | Check lengths first, after any cleaning |
Using split("") on user text | Emoji are cut in half; wrong matches are possible | Use [...str], Array.from(str) or for...of |
Cleaning with /[^a-z0-9]/g | Accents and non-English scripts vanish; "नमस्ते" matches "!!!" | Use /[^\p{L}\p{M}\p{N}]/gu and reject empty results |
| Comparing "é" from two sources | Same-looking strings have different lengths | Call normalize("NFC") on both inputs |
| Joining counts without a separator | Different words share a group key | Use counts.join(",") |
My Opinion
Make the Map frequency counter your default answer. It is O(n), handles any character that for...of can read, and the code says exactly what it does. In an interview, mention the sort version as the simpler alternative and explain why you chose counting.
Don't look down on sort-and-compare. For short words it is clear and fast enough, and it is the natural way to build group-anagram keys. Just use [...str] instead of split(""), so it stays correct for emoji.
Write the rules down before the code. Case, spaces, punctuation, digits and empty strings are product decisions, not bugs. A one-line comment at the top of the function saves a long argument later.
Normalise any text that a person typed. Names and phrases come from phones, laptops and copy-paste, and they will not always use the same form of "é". normalize("NFC") is one cheap call that removes a whole class of confusing bugs.
Test the awkward pairs, not just "listen" and "silent". "aab"/"abb", two empty strings, mixed case, an emoji and an accented letter together catch nearly every mistake in this problem.
Try It Yourself
Work these out on paper first, then paste the functions from this post into your browser console (press F12, then open Console) to check. Answers are below.
1. isAnagram("rat", "car")
2. isAnagram("Listen", "Silent")
3. isPhraseAnagram("Listen", "Silent")
4. isPhraseAnagram("Debit card", "Bad credit")
5. bruteIsAnagram("aab", "abb") from the original post: what does it return, and why?
6. "a😀".length and [..."a😀"].length
7. groupAnagrams(["listen", "silent", "enlist", "google", "gogole"])
8. Why can the count-down solution skip checking that every count is 0 at the end?
Show answers
1. false → same length, but "c" is not in "rat"
2. false → "L" and "l" are different characters; nothing is lower-cased
3. true → normalise() lower-cases both strings first
4. true → spaces are removed, then both become "debitcard" / "badcredit"
5. true → it only checks that each letter exists, never uses it up
6. 3 and 2 → the emoji is two code units but one code point
7. [ [ 'listen', 'silent', 'enlist' ], [ 'google', 'gogole' ] ]
8. Equal lengths + no count ever going below 0 means every unit was used exactly once
Frequently Asked Questions
Which approach do interviewers prefer?
Most expect the frequency-count solution because it is O(n) and shows you know the counting pattern. A sort-based answer is still correct; state its O(n log n) cost and offer the counting version as the improvement.
Should I use an object or a Map for counting?
Both work for single characters. A Map is safer for arbitrary keys like whole words, because a plain object inherits properties such as constructor. Object.create(null) is another way to get an object without inherited keys.
Can anagrams contain spaces or punctuation?
Only if your rules say so. Classic phrase anagrams like "Dormitory" and "Dirty room!" ignore case, spaces and punctuation, so clean both strings first and do the length check afterwards.
What is the space complexity of the counting solution?
O(k), where k is the number of distinct characters. For lowercase English letters k is at most 26, so in practice it is constant. The sort approach needs O(n) for the character arrays.
Key Takeaways
- Two strings are anagrams when they have the same characters with the same counts; order does not matter.
- Check lengths first, and do it after any cleaning step.
- Sort-and-compare is O(n log n) and short; frequency counting is O(n) and the usual interview answer.
- A nested-loop check that does not use letters up is wrong: it calls
"aab"and"abb"anagrams. - Write down your rules for case, spaces, punctuation and empty strings, and keep them in one function.
- Avoid
split("")on real text; use[...str]orfor...of, andnormalize("NFC")for accented letters. - Group anagrams by a shared key in a
Map: sorted letters, or comma-joined counts for a to z.
Next, practise the same habit of picking the right data structure on another array classic: finding prime numbers in an array.
References
- MDN: Map
- MDN: String.prototype.normalize()
- MDN: UTF-16 characters, Unicode code points and grapheme clusters
- MDN: Intl.Segmenter

0 Comments