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

  1. Built-ins: [...str].reverse().join(""). Clear and O(n).
  2. Loop from the end: build the result character by character. Shows you can do it without helpers, which interviewers sometimes ask for.
  3. Two pointers on an array: swap characters from both ends towards the middle; the classic in-place approach in languages with mutable strings.
  4. 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

  • "😀".length is 2: JavaScript strings are UTF-16, and emoji use surrogate pairs. split("") splits the pair and produces broken characters when reversed.
  • Spread and for...of iterate 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("");
2
3function reverseLoop(s) {
4 let out = "";
5 for (let i = s.length - 1; i >= 0; i--) out += s[i]; // code units: fine for plain text
6 return out;
7}
8
9function 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}
14
15const reverseGraphemes = (s) =>
16 Array.from(new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(s), (x) => x.segment)
17 .reverse()
18 .join("");
19
20console.log(reverse("hello"), reverseLoop("hello"), reverseTwoPointers("hello")); // olleh olleh olleh
21
22// Unicode edge cases
23console.log("😀".length); // 2 - one emoji, two UTF-16 code units
24console.log(reverseLoop("ab😀") === "😀ba"); // false - surrogate pair broken
25console.log(reverse("ab😀")); // 😀ba
26console.log(reverse("🇬🇧!") === "!🇬🇧"); // false - a flag is two code points
27console.log(reverseGraphemes("🇬🇧!")); // !🇬🇧
28
29// Follow-up: reverse words, not characters
30console.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.

Open in study app