These are the notes for JavaScript Coding Questions, episode 11, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Today we start strings with three classics: reverse a string (and why the famous one-liner breaks emojis), a palindrome check that ignores case and punctuation, and counting vowels.
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. In error messages, the file path is shortened to main.js.
Q1: Reverse a string
Problem. Return the characters of a string in the opposite order.
"chai" → "iahc"
"I love 🍕" → "🍕 evol I"
"" → ""
Real life: any app where people type messages, and people type emojis all the time.
Think out loud
- Arrays have
reverse(). Do strings? - Edge cases: an empty string, emojis, and an emoji with a skin tone (👍🏽).
The first guess: s.reverse()
const s = "chai";
console.log(s.reverse());
main.js:2
console.log(s.reverse());
^
TypeError: s.reverse is not a function
Why: a string is not an array. And strings in JavaScript are immutable: they can never be changed in place (s[0] = "C" silently does nothing). So there is no reverse on strings; we always build a new string.
The famous one-liner: split("").reverse().join("")
function reverse(s) {
return s.split("").reverse().join("");
}
console.log(reverse("chai"));
console.log(reverse("racecar"));
console.log(reverse("I love 🍕"));
iahc
racecar
�� evol I
The pizza became two � replacement characters. Let's look inside:
console.log("🍕".length);
console.log("🍕".split(""));
console.log([..."🍕"]);
2
[ '\ud83c', '\udf55' ]
[ '🍕' ]
Code units, code points and graphemes
Think of a box of sweets.
- Inside, a JavaScript string is a list of 16-bit pieces called UTF-16 code units. Most letters fit in one. An emoji needs two (a surrogate pair).
lengthcounts code units, so"🍕".lengthis 2.split("")cuts between every code unit, like cutting every sweet in half; reversed, the two halves are in the wrong order and no longer make a valid character. - A string's iterator (used by
for...ofand spread[...s]) walks by code point: one whole Unicode character at a time. It picks up whole sweets. - Some things a person sees as one character are several code points: 👍🏽 is a thumbs up plus a skin-tone modifier, and the Hindi word नमस्ते has letters with vowel signs attached. What a person sees as one character is a grapheme.
Intl.Segmenterwithgranularity: "grapheme"splits text into graphemes.
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
const visibleLength = s => [...seg.segment(s)].length;
for (const s of ["chai", "🍕", "👍🏽", "नमस्ते"]) {
console.log(s, s.length, [...s].length, visibleLength(s));
}
chai 4 4 4
🍕 2 1 1
👍🏽 4 2 1
नमस्ते 6 6 3
(Columns: the string, code units, code points, graphemes.)
Fix 1: spread instead of split
function reverse(s) {
return [...s].reverse().join("");
}
console.log(reverse("chai"));
console.log(reverse("I love 🍕"));
console.log(reverse("👍🏽 ok"), [..."👍🏽"]);
iahc
🍕 evol I
ko 🏽👍 [ '👍', '🏽' ]
The pizza is whole, but the thumbs up and its skin tone came apart: spread sees two code points.
Fix 2: Intl.Segmenter (graphemes)
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
function reverse(s) {
return [...seg.segment(s)].map(p => p.segment).reverse().join("");
}
console.log(reverse("chai"));
console.log(reverse("I love 🍕"));
console.log(reverse("👍🏽 ok"));
console.log(reverse("") === "");
iahc
🍕 evol I
ko 👍🏽
true
seg.segment(s) gives pieces like { segment: "👍🏽", index: 0, ... }; map(p => p.segment) takes the text of each.
Complexity: a pass to split, one to reverse, one to join: O(n) time, O(n) space (a new string must be built). In an interview: write split("").reverse().join(""), then say it breaks emojis and give [...s] or Intl.Segmenter.
Q2: Valid palindrome (ignore case and punctuation)
Problem. A palindrome reads the same forwards and backwards. Look only at letters and digits, ignoring case.
"racecar" → true
"Madam" → true
"Never odd or even" → true
"A man, a plan, a canal: Panama" → true
"chai" → false
Real life: names like NITIN, or the word MALAYALAM on a nameplate.
The obvious attempt: compare with the reverse
function isPalindrome(s) {
return s === [...s].reverse().join("");
}
console.log(isPalindrome("racecar"));
console.log(isPalindrome("Madam"));
console.log(isPalindrome("Never odd or even"));
console.log(isPalindrome("A man, a plan, a canal: Panama"));
true
false
false
false
Why: === compares exactly: "M" is not "m", and spaces and commas land in different places when reversed.
Fix 1: clean, then compare
toLowerCase() makes every letter small. The regular expression /[^a-z0-9]/g matches any character that is not (^ inside [...]) a to z or 0 to 9; the g flag means every match. replace with "" deletes them.
function isPalindrome(s) {
const clean = s.toLowerCase().replace(/[^a-z0-9]/g, "");
return clean === [...clean].reverse().join("");
}
console.log(isPalindrome("racecar"));
console.log(isPalindrome("Madam"));
console.log(isPalindrome("Never odd or even"));
console.log(isPalindrome("A man, a plan, a canal: Panama"));
console.log(isPalindrome("chai"), isPalindrome(""), isPalindrome("!!"));
true
true
true
true
false true true
An empty string and a string of only symbols count as palindromes: after cleaning there is nothing that reads differently. Correct, but it builds a cleaned copy and a reversed copy: O(n) extra space.
Fix 2: two pointers, no copies
Two friends read a long nameplate, one from each end (i and j). A friend on a space or comma steps past it on their own side. They call out their letters: different (ignoring case) means not a palindrome; the same means both step toward the middle. When they meet, every pair matched.
function isPalindrome(s) {
const ok = c => /[a-z0-9]/i.test(c);
let i = 0, j = s.length - 1;
while (i < j) {
if (!ok(s[i])) { i++; continue; }
if (!ok(s[j])) { j--; continue; }
if (s[i].toLowerCase() !== s[j].toLowerCase()) return false;
i++; j--;
}
return true;
}
console.log(isPalindrome("racecar"));
console.log(isPalindrome("Madam"));
console.log(isPalindrome("Never odd or even"));
console.log(isPalindrome("A man, a plan, a canal: Panama"));
console.log(isPalindrome("chai"), isPalindrome(""), isPalindrome("!!"));
true
true
true
true
false true true
ok tests one character; the i flag makes the regex ignore case. O(n) time (each pointer crosses each character at most once) and O(1) extra space. This version works on code units, which is fine because only ASCII letters and digits are compared.
Q3: Count the vowels
Problem. Count a, e, i, o, u in a string, capitals included.
"samosa" → 3
"ICE CREAM" → 4
"rhythm" → 0
Real life: a spelling game for kids, or a rule in a password checker.
The obvious attempt: five comparisons
function countVowels(s) {
let count = 0;
for (const c of s) {
if (c === "a" || c === "e" || c === "i" || c === "o" || c === "u") count++;
}
return count;
}
console.log(countVowels("samosa"));
console.log(countVowels("SyntaxPilot"));
console.log(countVowels("ICE CREAM"));
3
3
0
Why: "I" is not "i". SyntaxPilot only worked by luck (its capital P is not a vowel).
Fix: lowercase + a Set
const VOWELS = new Set("aeiou");
function countVowels(s) {
let count = 0;
for (const c of s.toLowerCase()) {
if (VOWELS.has(c)) count++;
}
return count;
}
console.log(countVowels("samosa"));
console.log(countVowels("SyntaxPilot"));
console.log(countVowels("ICE CREAM"));
console.log(countVowels(""), countVowels("rhythm"));
3
3
4
0 0
new Set("aeiou") iterates the string, so it is a Set of five letters; has checks a letter in one step. O(n) time, O(1) space for the Set (strictly, toLowerCase() makes a copy; lowercase each character instead to avoid it).
The regex one-liner, and null
const countVowels = s => s.match(/[aeiou]/gi).length;
console.log(countVowels("ICE CREAM"));
console.log(countVowels("rhythm"));
4
main.js:1
const countVowels = s => s.match(/[aeiou]/gi).length;
^
TypeError: Cannot read properties of null (reading 'length')
Why: when nothing matches, match with the g flag returns null, not []. The nullish coalescing operator ?? gives a fallback when the left side is null or undefined:
const countVowels = s => (s.match(/[aeiou]/gi) ?? []).length;
console.log(countVowels("ICE CREAM"));
console.log(countVowels("rhythm"), countVowels(""));
4
0 0
Complexity summary
| Question | Approach | Time | Extra space |
|---|---|---|---|
| Reverse | split("") + reverse + join |
O(n) | O(n), breaks emojis |
| Reverse | [...s] + reverse + join |
O(n) | O(n), splits skin tones |
| Reverse | Intl.Segmenter |
O(n) | O(n), correct graphemes |
| Palindrome | clean + compare with reverse | O(n) | O(n) |
| Palindrome | two pointers | O(n) | O(1) |
| Vowels | lowercase + Set | O(n) | O(1) besides the lowercase copy |
| Vowels | match + ?? [] |
O(n) | O(v) for the matches |
Common mistakes (and the exact outputs)
| Mistake | Code | What you see | Why | Fix |
|---|---|---|---|---|
| Reversing a string directly | s.reverse() |
TypeError: s.reverse is not a function |
strings are not arrays, and immutable | [...s].reverse().join("") |
split("") on emojis |
"I love 🍕".split("") |
�� evol I after reversing |
splits UTF-16 code units | [...s] or Intl.Segmenter |
Trusting length |
"🍕".length |
2 |
counts code units | [...s].length or segments |
| Spread on combined emojis | [..."👍🏽"] |
[ '👍', '🏽' ] |
two code points, one grapheme | Intl.Segmenter |
| Raw comparison for palindromes | s === reversed |
false for "Madam" |
case and punctuation count | clean first, or two pointers |
| Forgetting capitals | c === "a" \|\| ... |
0 for "ICE CREAM" |
"I" !== "i" |
toLowerCase() + a Set |
Using match without a fallback |
s.match(/[aeiou]/gi).length |
TypeError: Cannot read properties of null (reading 'length') |
no match returns null |
(s.match(...) ?? []).length |
Mini project: the nameplate checker
A sign maker gets a list of names. For each, report whether it reads the same both ways, how many vowels it has, and the name reversed.
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
const reverse = s => [...seg.segment(s)].map(p => p.segment).reverse().join("");
const clean = s => s.toLowerCase().replace(/[^a-z0-9]/g, "");
const isPalindrome = s => clean(s) === [...clean(s)].reverse().join("");
const vowels = s => (s.match(/[aeiou]/gi) ?? []).length;
const names = ["Nitin", "Asha", "Malayalam", "Hannah 🌸", "Rhythm Store"];
for (const n of names) {
const mark = isPalindrome(n) ? "palindrome" : "-";
console.log(`${n.padEnd(14)} ${mark.padEnd(11)} vowels: ${vowels(n)} mirror: ${reverse(n)}`);
}
Nitin palindrome vowels: 2 mirror: nitiN
Asha - vowels: 2 mirror: ahsA
Malayalam palindrome vowels: 4 mirror: malayalaM
Hannah 🌸 palindrome vowels: 2 mirror: 🌸 hannaH
Rhythm Store - vowels: 2 mirror: erotS mhtyhR
(padEnd counts code units, so the line with the emoji looks one space short; padding by graphemes would fix it.)
Your turn: reverse each word (solution)
Problem. Reverse every word, but keep the words in their order. "chai is hot" → "iahc si toh". Extra spaces must survive.
Solution
split(" ") keeps empty strings between double spaces, so joining with " " puts every space back exactly where it was.
function reverseWords(s) {
return s.split(" ").map(w => [...w].reverse().join("")).join(" ");
}
console.log(reverseWords("chai is hot"));
console.log(JSON.stringify(reverseWords(" two spaces ")));
console.log(JSON.stringify(reverseWords("")));
iahc si toh
" owt secaps "
""
O(n) time, O(n) space. Use Intl.Segmenter inside map if words can contain emojis with modifiers.
Practice questions (with solutions)
1. Palindrome with at most one deletion: can the string become a palindrome by deleting at most one character?
Solution
Walk two pointers. At the first mismatch you get one chance: skip the left character or the right one, and check the rest with a plain palindrome check.
function validPalindromeOneDelete(s) {
const isPal = (i, j) => {
while (i < j) if (s[i++] !== s[j--]) return false;
return true;
};
let i = 0, j = s.length - 1;
while (i < j) {
if (s[i] !== s[j]) return isPal(i + 1, j) || isPal(i, j - 1);
i++; j--;
}
return true;
}
console.log(validPalindromeOneDelete("abca"), validPalindromeOneDelete("racecar"));
console.log(validPalindromeOneDelete("abc"), validPalindromeOneDelete("deeee"));
true true
false true
O(n) time (at most two extra scans), O(1) space.
2. Count vowels, consonants, digits and everything else.
Solution
function countKinds(s) {
const counts = { vowels: 0, consonants: 0, digits: 0, other: 0 };
for (const c of s.toLowerCase()) {
if ("aeiou".includes(c)) counts.vowels++;
else if (c >= "a" && c <= "z") counts.consonants++;
else if (c >= "0" && c <= "9") counts.digits++;
else counts.other++;
}
return counts;
}
console.log(countKinds("Flat 4B, MG Road 560001"));
{ vowels: 3, consonants: 8, digits: 7, other: 5 }
Comparing one-character strings with >= and <= compares their character codes, so c >= "a" && c <= "z" means "a lowercase letter". "aeiou".includes(c) is fine here: the string has only five characters.
3. Is a string made only of vowels?
Solution
const allVowels = s => s.length > 0 && /^[aeiou]+$/i.test(s);
console.log(allVowels("aeiou"), allVowels("AiE"), allVowels("ai2"), allVowels(""));
true true false false
^ and $ anchor the pattern to the start and end, so the whole string must match; + means one or more.
Quick quiz
1. (From the video.) What does this print?
const s = "hi🍕";
console.log(s.length, [...s].length);
(A) 3 3 (B) 4 3 (C) 3 4 (D) 4 4
Answer
(B) 4 3. length counts UTF-16 code units (h, i, and two for the emoji); spread counts code points (h, i, 🍕).
2. What does this print?
const s = "chai";
s[0] = "C";
console.log(s, s[0], s.at(-1));
Answer
chai c i
Strings are immutable, so the assignment is silently ignored (in strict mode it throws a TypeError). s.at(-1) is the last character.
3. What does "I love 🍕".split("").length give compared with [..."I love 🍕"].length?
Answer
9 and 8: seven characters plus the emoji, which is two code units but one code point.
Interview questions
- Reverse a string in JavaScript.
[...s].reverse().join(""); strings have noreversebecause they are immutable and not arrays. - What's wrong with
split("")? It splits UTF-16 code units, breaking emojis and other characters outside the Basic Multilingual Plane. - Code unit vs code point vs grapheme? 16-bit piece / one Unicode character / what a person sees as one character.
- How do you get the visible length of a string? Count
Intl.Segmentergraphemes:[...seg.segment(s)].length. - Check a palindrome ignoring case and punctuation. Clean with
toLowerCase().replace(/[^a-z0-9]/g, "")and compare, or two pointers that skip non-alphanumerics. - Why prefer two pointers? O(1) extra space and an early exit on the first mismatch.
- Palindrome with one deletion allowed? At the first mismatch, try skipping either side once.
- Count vowels efficiently. One pass, lowercase, a Set of vowels: O(n).
- What does
"rhythm".match(/[aeiou]/g)return?null, so guard with?? []. - Are JavaScript strings mutable? No: every "change" makes a new string.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Immutable | Can't be changed in place | s[0] = "C" does nothing |
split(sep) |
Breaks a string into an array | "a,b".split(",") → ["a", "b"] |
join(sep) |
Joins an array into a string | ["a", "b"].join("") → "ab" |
| UTF-16 | How JavaScript stores strings: 16-bit pieces | "🍕" is 2 pieces |
| Code unit | One 16-bit piece; what length counts |
"🍕".length → 2 |
| Surrogate pair | Two code units that together make one character | '\ud83c', '\udf55' |
| Code point | One Unicode character; what for...of and spread give |
[..."🍕"] → ['🍕'] |
| Grapheme | What a person sees as one character | 👍🏽 |
| Skin-tone modifier | A code point that changes the emoji before it | 🏽 |
Intl.Segmenter |
Built-in that splits text into graphemes, words or sentences | granularity: "grapheme" |
| Replacement character | �, shown for broken text |
half an emoji |
| Palindrome | Reads the same both ways | "racecar" |
toLowerCase() |
A copy with small letters | "ICE".toLowerCase() → "ice" |
| Regular expression | A pattern for matching text | /[^a-z0-9]/g |
Character class [...] |
Any one character from the set; ^ first means "not" |
[aeiou], [^a-z] |
g and i flags |
Every match / ignore case | /[aeiou]/gi |
replace(re, "") |
Delete every match | strip punctuation |
test |
Does the regex match? true/false |
/[a-z]/i.test("Q") |
match |
The matches as an array, or null |
"chai".match(/[aeiou]/g) → ['a', 'i'] |
| Two pointers | Two indexes moving through the data | i from the left, j from the right |
| Set | Unique values with fast has |
new Set("aeiou") |
Nullish coalescing (??) |
Fallback when the left is null/undefined |
x ?? [] |
at(-1) |
Item counted from the end | "chai".at(-1) → "i" |
padEnd(n) |
Pads a string with spaces to length n | "ab".padEnd(4) → "ab " |
Summary
- Reverse: strings are immutable and have no
reverse.split("")cuts emojis into UTF-16 halves;[...s]keeps code points;Intl.Segmenterkeeps graphemes (skin tones, Hindi letters with vowel signs). - Palindrome: lowercase and strip non-alphanumerics, then compare; or use two pointers that skip punctuation, for O(1) extra space.
- Vowels: lowercase once and check a Set of vowels.
matchreturnsnullwhen nothing matches, so use?? [].
Next episode: String questions II: anagram check (sorting vs a counting Map), the first non-repeating character, and the most frequent character.