JavaScriptEasy
Reverse a string
The idiomatic solution is [...str].reverse().join(""); use spread rather than split("") so characters outside the Basic Multilingual Plane (like emoji) are not broken, and use Intl.Segmenter if you must keep complex emoji and accented clusters intact.
Approaches
- Built-ins:
[...str].reverse().join(""). Clear and O(n). - Loop from the end: build the result character by character. Shows you can do it without helpers, which interviewers sometimes ask for.
- Two pointers on an array: swap characters from both ends towards the middle; the classic in-place approach in languages with mutable strings.
- Recursion:
reverse(s.slice(1)) + s[0]. Elegant but O(n²) because of repeated slicing, and it can overflow the stack on long strings. Mention why you would not use it in production.
Unicode details interviewers love
"😀".lengthis 2: JavaScript strings are UTF-16, and emoji use surrogate pairs.split("")splits the pair and produces broken characters when reversed.- Spread and
for...ofiterate by code points, fixing surrogate pairs. - Some visible characters are several code points (flags, families, skin tones,
e+ combining accent). Only grapheme segmentation (Intl.Segmenter) keeps those intact.
Complexity
All the linear approaches are O(n) time and O(n) space (strings are immutable in JavaScript, so a new string is always created).
Follow-ups
Reverse the words in a sentence (split(" ").reverse().join(" ")), or reverse in place in an array of characters with two pointers.
Code example
js
1const reverse = (s) => [...s].reverse().join("");23function reverseLoop(s) {4 let out = "";5 for (let i = s.length - 1; i >= 0; i--) out += s[i]; // code units: fine for plain text6 return out;7}89function reverseTwoPointers(s) {10 const chars = [...s];11 for (let i = 0, j = chars.length - 1; i < j; i++, j--) [chars[i], chars[j]] = [chars[j], chars[i]];12 return chars.join("");13}1415const reverseGraphemes = (s) =>16 Array.from(new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(s), (x) => x.segment)17 .reverse()18 .join("");1920console.log(reverse("hello"), reverseLoop("hello"), reverseTwoPointers("hello")); // olleh olleh olleh2122// Unicode edge cases23console.log("😀".length); // 2 - one emoji, two UTF-16 code units24console.log(reverseLoop("ab😀") === "😀ba"); // false - surrogate pair broken25console.log(reverse("ab😀")); // 😀ba26console.log(reverse("🇬🇧!") === "!🇬🇧"); // false - a flag is two code points27console.log(reverseGraphemes("🇬🇧!")); // !🇬🇧2829// Follow-up: reverse words, not characters30console.log("the quick brown fox".split(" ").reverse().join(" ")); // fox brown quick the
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.