SyntaxPilot
Courses/JavaScript Coding Questions/Lesson 12
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript Coding Questions · Lesson 12 of 30

String questions II

anagram check (sort vs counting map)first non-repeating charactermost frequent character

These are the notes for JavaScript Coding Questions, episode 12, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Three string questions: is one word an anagram of another, the first non-repeating character, and the most frequent character. One small tool solves all three: a counting Map (a frequency counter).

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.

Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Plain modern JavaScript, no packages.

About the timings. Lines like check: 896.009ms are copied from a real run on one machine; your numbers will differ. What matters is the size of the gap.

Q1: Are two words anagrams?

Problem. Two words are anagrams if they use exactly the same letters, the same number of times, in any order. Ignore case.

"listen" / "silent"      → true
"aab" / "abb"            → false (two a's vs two b's)
"cat" / "cats"           → false
"Dormitory" / "DirtyRoom" → true

Real life: the jumbled-word puzzle in the newspaper, or any word game.

Think out loud

  • Same letters is not enough: the counts must match.
  • Edge cases: repeated letters, different lengths, capitals, two empty strings.

The obvious attempt: includes

function isAnagram(a, b) {
  for (const c of a) {
    if (!b.includes(c)) return false;
  }
  return true;
}
console.log(isAnagram("listen", "silent"));
console.log(isAnagram("aab", "abb"));
console.log(isAnagram("cat", "cats"));
true
true
true

Why it fails: includes only asks "is this letter there at all?", never "how many times?". And the extra s in cats is never checked, because we only loop over a.

Fix 1: sort and compare

If two words are anagrams, sorting their letters gives the same string.

function isAnagram(a, b) {
  const sort = s => [...s.toLowerCase()].sort().join("");
  return sort(a) === sort(b);
}
console.log(isAnagram("listen", "silent"));
console.log(isAnagram("aab", "abb"));
console.log(isAnagram("cat", "cats"));
console.log(isAnagram("Dormitory", "DirtyRoom"));
true
false
false
true

The default sort() (compare as strings) is fine here: we only need the same order on both sides. But sorting costs O(n log n):

function isAnagram(a, b) {
  const sort = s => [...s.toLowerCase()].sort().join("");
  return sort(a) === sort(b);
}
const big1 = "abcdefghij".repeat(300000);
const big2 = [...big1].reverse().join("");
console.time("check");
console.log(isAnagram(big1, big2));
console.timeEnd("check");
true
check: 896.009ms

Fix 2: a counting Map (ticking off a tiffin order)

Check a tiffin delivery: write the order down with counts (roti × 2, dal × 1); tick off each item as it comes out of the bag; an item with nothing left to tick (too many, or never ordered) means the delivery is wrong. And if the bags have a different number of items, they can't match.

function isAnagram(a, b) {
  if (a.length !== b.length) return false;
  const count = new Map();
  for (const c of a.toLowerCase()) count.set(c, (count.get(c) ?? 0) + 1);
  for (const c of b.toLowerCase()) {
    if (!count.get(c)) return false;
    count.set(c, count.get(c) - 1);
  }
  return true;
}
console.log(isAnagram("listen", "silent"));
console.log(isAnagram("aab", "abb"));
console.log(isAnagram("cat", "cats"));
console.log(isAnagram("Dormitory", "DirtyRoom"), isAnagram("", ""));
const big1 = "abcdefghij".repeat(300000);
const big2 = [...big1].reverse().join("");
console.time("check");
console.log(isAnagram(big1, big2));
console.timeEnd("check");
true
false
false
true true
true
check: 155.389ms
  • count.get(c) ?? 0 gives 0 for a letter not seen yet.
  • !count.get(c) is true for both undefined (never ordered) and 0 (all ticked off).
  • With equal lengths and no count going below zero, every count ends at exactly zero.

Complexity: two passes, O(n) time. The Map holds one entry per different letter; call that k: O(k) space (at most 26 for English letters, which is constant).

Q2: First non-repeating character

Problem. Return the first character that appears exactly once, or null if there is none.

"swiss"  → "w"   (s appears 3 times)
"aabbc"  → "c"
"aabb"   → null

Real life: in a class register, the first student whose name nobody else shares.

The obvious attempt: indexOf(c) === i

function firstUnique(s) {
  for (let i = 0; i < s.length; i++) {
    if (s.indexOf(s[i]) === i) return s[i];
  }
  return null;
}
console.log(firstUnique("swiss"));
console.log(firstUnique("aabbc"), firstUnique("aabb"));
s
a a

Why: indexOf(c) === i only means "this is the first time I see this character". The first character is always seen for the first time, so it is always returned.

Correct but slow: indexOf === lastIndexOf

A character appears once exactly when its first and last positions are equal. The big test has 40,000 different characters written twice, then !:

function firstUnique(s) {
  for (let i = 0; i < s.length; i++) {
    if (s.indexOf(s[i]) === s.lastIndexOf(s[i])) return s[i];
  }
  return null;
}
console.log(firstUnique("swiss"));
console.log(firstUnique("aabbc"), firstUnique("aabb"));
const chars = Array.from({ length: 40000 }, (_, i) => String.fromCharCode(0x4e00 + i));
const big = chars.join("") + chars.join("") + "!";
console.time("first");
console.log(firstUnique(big));
console.timeEnd("first");
w
c null
!
first: 727.542ms

(String.fromCharCode(0x4e00 + i) just makes 40,000 different characters; 0x4e00 is where the Chinese characters start in Unicode.)

Why it is slow: indexOf and lastIndexOf each scan the string. Inside a loop over the string, that's n scans of length up to n: O(n²), hidden inside two innocent method calls. With only a few different characters the scans stop early, which is why small tests look fast.

Fix: count, then read in order (the class register)

Tally every name in one pass; then read the register from the top and stop at the first name with a tally of 1. The second pass goes over the string, not the Map, so "first" means first in the string.

function firstUnique(s) {
  const count = new Map();
  for (const c of s) count.set(c, (count.get(c) ?? 0) + 1);
  for (const c of s) {
    if (count.get(c) === 1) return c;
  }
  return null;
}
console.log(firstUnique("swiss"));
console.log(firstUnique("aabbc"), firstUnique("aabb"));
console.log(firstUnique(""), firstUnique("chai"));
const chars = Array.from({ length: 40000 }, (_, i) => String.fromCharCode(0x4e00 + i));
const big = chars.join("") + chars.join("") + "!";
console.time("first");
console.log(firstUnique(big));
console.timeEnd("first");
w
c null
null c
!
first: 27.029ms

Complexity: two passes, O(n) time, O(k) space for k different characters.

Q3: Most frequent character

Problem. Return the character that appears most often and how many times, ignoring spaces. On a tie, return the one that appears first in the string.

"banana"              → a, 3 times
"to be or not to be"  → o, 4 times
"2121"                → 2, 2 times (ties with 1, but 2 comes first)

Real life: counting votes for class monitor (blank slips don't count).

The obvious attempt: a plain object and for...in

JSON.stringify prints strings with quotes, so a space is visible.

function mostFrequent(s) {
  const count = {};
  for (const c of s) count[c] = (count[c] ?? 0) + 1;
  let best = "", max = 0;
  for (const c in count) {
    if (count[c] > max) { max = count[c]; best = c; }
  }
  return best;
}
console.log(JSON.stringify(mostFrequent("banana")));
console.log(JSON.stringify(mostFrequent("to be or not to be")));
console.log(JSON.stringify(mostFrequent("2121")));
"a"
" "
"1"

Two bugs: the spaces were counted (there are five), and the tie went to "1" instead of "2". The second one is surprising, so test the key order directly:

const count = {};
count["2"] = 2;
count["1"] = 2;
count["b"] = 1;
count["a"] = 1;
console.log(Object.keys(count));
const m = new Map([["2", 2], ["1", 2], ["b", 1], ["a", 1]]);
console.log([...m.keys()]);
[ '1', '2', 'b', 'a' ]
[ '2', '1', 'b', 'a' ]

Why: objects follow a fixed key order: keys that look like whole numbers (integer-like keys, also called array indices) come first in ascending number order, then all other string keys in insertion order. for...in, Object.keys and JSON.stringify all use this order. A Map always keeps insertion order.

Fix: skip spaces, use a Map, strictly greater wins

function mostFrequent(s) {
  const count = new Map();
  for (const c of s) {
    if (c !== " ") count.set(c, (count.get(c) ?? 0) + 1);
  }
  let best = null, max = 0;
  for (const [c, n] of count) {
    if (n > max) { max = n; best = c; }
  }
  return { char: best, times: max };
}
console.log(JSON.stringify(mostFrequent("banana")));
console.log(JSON.stringify(mostFrequent("to be or not to be")));
console.log(JSON.stringify(mostFrequent("2121")));
console.log(JSON.stringify(mostFrequent("abba")), JSON.stringify(mostFrequent("")));
{"char":"a","times":3}
{"char":"o","times":4}
{"char":"2","times":2}
{"char":"a","times":2} {"char":null,"times":0}
  • The Map's entries come in first-appearance order, and only a strictly bigger count (>, not >=) replaces the leader, so ties go to the character that appears first ("abba" → a).
  • Tracking the leader while counting would answer a different question ("first to reach the top count"): for "abba" it would give b.

Complexity: one pass to count, one over at most k entries: O(n) time, O(k) space.

Complexity summary

Question Approach Time Extra space
Anagram includes per letter O(n · m), and wrong O(1)
Anagram sort + compare O(n log n) O(n)
Anagram counting Map O(n) O(k)
First unique indexOf + lastIndexOf O(n²) O(1)
First unique count, then second pass O(n) O(k)
Most frequent Map + strict > O(n) O(k)

Common mistakes (and the exact outputs)

Mistake Code What you see Why Fix
Presence instead of counts b.includes(c) for each c of a true for "aab"/"abb" counts are ignored counting Map, lengths first
Forgetting the length check loop over a only true for "cat"/"cats" extra letters in b never checked if (a.length !== b.length) return false
"First seen" as "unique" s.indexOf(s[i]) === i "s" for "swiss" always true for the first character count, then a second pass
Hidden O(n²) indexOf + lastIndexOf in a loop first: 727.542ms for 80,001 characters each call scans the string count once
Object key order for (const c in count) "1" for "2121" integer-like keys come first, sorted a Map
Counting spaces no skip " " for "to be or not to be" spaces are characters too if (c !== " ")
>= for the leader if (n >= max) ties go to the last character equal counts replace the leader if (n > max)

Mini project: username clean-up

A chat app wants to spot usernames that are anagrams of each other (likely confusing look-alikes) and show each name's first unique letter as its avatar letter.

// Chat usernames typed at sign-up: spot anagram duplicates and each name's first unique letter.
const names = ["ravi", "vira", "asha", "haas", "neha", "anil", "lina", "nitin"];
const key = w => [...w].sort().join("");
const groups = Map.groupBy(names, key);
for (const [k, list] of groups) {
  if (list.length > 1) console.log(`anagram group ${k}: ${list.join(", ")}`);
}
function firstUnique(s) {
  const count = new Map();
  for (const c of s) count.set(c, (count.get(c) ?? 0) + 1);
  for (const c of s) if (count.get(c) === 1) return c;
  return null;
}
console.log(names.map(n => `${n}:${firstUnique(n) ?? "-"}`).join("  "));
anagram group airv: ravi, vira
anagram group aahs: asha, haas
anagram group ailn: anil, lina
ravi:r  vira:v  asha:s  haas:h  neha:n  anil:a  lina:l  nitin:t

The sorted letters are the anagram key: every anagram has the same key, so grouping by it (episode 10's Map.groupBy) collects anagrams together. This is the "group anagrams" question of episode 28.

Your turn: ransom note (solution)

Problem. Can you build note by cutting letters out of magazine, using each letter at most once? canBuild("chai", "achiever") → true; canBuild("aa", "ab") → false.

Solution

It is the tiffin check, but the magazine may have extra letters, so there is no length-equality check: count the magazine, then tick off the note.

function canBuild(note, magazine) {
  const count = new Map();
  for (const c of magazine) count.set(c, (count.get(c) ?? 0) + 1);
  for (const c of note) {
    if (!count.get(c)) return false;
    count.set(c, count.get(c) - 1);
  }
  return true;
}
console.log(canBuild("chai", "achiever"), canBuild("aa", "ab"));
console.log(canBuild("", "xyz"), canBuild("tea", ""));
true false
true false

O(n + m) time, O(k) space. An empty note can always be built.

Practice questions (with solutions)

1. Last non-repeating character.

Solution

Count as before; then walk the characters from the end.

function lastUnique(s) {
  const count = new Map();
  for (const c of s) count.set(c, (count.get(c) ?? 0) + 1);
  const chars = [...s];
  for (let i = chars.length - 1; i >= 0; i--) {
    if (count.get(chars[i]) === 1) return chars[i];
  }
  return null;
}
console.log(lastUnique("swiss"), lastUnique("aabbcdd"), lastUnique("aa"));
i c null

[...s] makes an array of code points, so walking backwards never splits an emoji.

2. The top k most frequent characters (ignoring spaces).

Solution
function topK(s, k) {
  const count = new Map();
  for (const c of s) if (c !== " ") count.set(c, (count.get(c) ?? 0) + 1);
  return [...count].sort((a, b) => b[1] - a[1]).slice(0, k);
}
console.log(topK("to be or not to be", 3));
console.log(topK("mississippi", 2));
[ [ 'o', 4 ], [ 't', 3 ], [ 'b', 2 ] ]
[ [ 'i', 4 ], [ 's', 4 ] ]

[...count] turns the Map into [char, count] pairs. sort is stable in JavaScript, so equal counts keep first-appearance order (b before e). O(n + k log k) time.

3. Are all words in a list anagrams of each other?

Solution
function allAnagrams(words) {
  const key = w => [...w.toLowerCase()].sort().join("");
  return words.every(w => key(w) === key(words[0]));
}
console.log(allAnagrams(["listen", "silent", "enlist", "tinsel"]));
console.log(allAnagrams(["listen", "silent", "lister"]));
console.log(allAnagrams([]));
true
false
true

every on an empty array is true (there is no word that breaks the rule).

Quick quiz

1. (From the video.) What does this print?

const o = { b: 1, 10: 1, a: 1, 2: 1 };
console.log(Object.keys(o));

(A) [ 'b', '10', 'a', '2' ] (B) [ '2', '10', 'b', 'a' ] (C) [ '10', '2', 'b', 'a' ] (D) [ 'a', 'b', '2', '10' ]

Answer

(B) [ '2', '10', 'b', 'a' ]. Integer-like keys first in ascending number order (2 before 10), then the other keys in insertion order.

2. What does this print?

console.log([..."Listen"].sort().join(""), [..."listen"].sort().join(""));
Answer
Leinst eilnst

Capital letters sort before small letters (their character codes are smaller), so lowercase both words before comparing.

3. Is isAnagram with a counting Map still correct without the length check?

Answer

No: isAnagram("cat", "ca") would tick off c and a and return true. The second loop only proves b fits inside a; equal lengths prove nothing is left over.

Interview questions

  1. Check if two strings are anagrams. Equal lengths, then a counting Map (or a 26-slot array for lowercase letters): O(n).
  2. Why not just sort? It works, but O(n log n) instead of O(n).
  3. What is a frequency counter? A Map (or object) from each value to how many times it appears.
  4. First non-repeating character in O(n)? Count, then scan the string again for the first count of 1.
  5. Why is indexOf inside a loop dangerous? Each call scans the string, so the loop becomes O(n²).
  6. Most frequent character with ties going to the first? Map (insertion order) + strict >.
  7. In what order does for...in visit keys? Integer-like keys ascending, then string keys in insertion order (symbols are skipped).
  8. When should you use a Map instead of an object for counting? Keys from user data, number-like keys whose order matters, or non-string keys.
  9. What is the space complexity of a counter over lowercase letters? O(26) = O(1).
  10. How do you group anagrams? Group by the sorted letters (the anagram key).

Glossary

Term Meaning Example
Anagram Same letters, same counts, any order listen / silent
Frequency counter A map from value to how many times it appears Map { 'a' => 3 }
Counting Map A frequency counter built with Map count.set(c, (count.get(c) ?? 0) + 1)
includes Is a value present? (linear scan) "chai".includes("h")
Map.get / Map.set Read / write a key's value count.get("a")
Nullish coalescing (??) Fallback when the left is null/undefined count.get(c) ?? 0
O(n log n) The cost of sorting [...s].sort()
O(k) Space that grows with the number of different values one entry per letter
Non-repeating / unique character Appears exactly once w in swiss
indexOf / lastIndexOf First / last position, or -1 "swiss".lastIndexOf("s") → 4
Hidden O(n²) A linear method call inside a loop indexOf in a for
String.fromCharCode The character for a code String.fromCharCode(65) → "A"
Integer-like key An object key that looks like a whole number "2", "10"
Property order Integer-like keys ascending, then insertion order { b, 10, a, 2 } → 2, 10, b, a
for...in Loops over an object's keys in property order for (const k in obj)
Insertion order The order keys were first added what a Map keeps
JSON.stringify A string version of a value, strings in quotes JSON.stringify(" ") → '" "'
Tie-break The rule for equal counts first appearance
Stable sort Equal items keep their order sort in JavaScript
Anagram key The sorted letters of a word listen → eilnst
every Do all items pass? (true for empty) [].every(f) → true

Summary

  • Anagrams need the same letters and the same counts. Sorting both and comparing is O(n log n); a counting Map (lengths first, count a, tick off b) is O(n).
  • First non-repeating character: indexOf === i is wrong and indexOf === lastIndexOf is a hidden O(n²). Count once, then read the string again in order: O(n).
  • Most frequent character: skip spaces; objects list integer-like keys first in number order, so use a Map for insertion order and a strict > so ties go to the first character.

Next episode: String questions III: capitalize every word, convert between camelCase and snake_case with regular expressions, and count words when there are extra spaces.