Reverse a string in O(n)
Implement reverseString(s) that returns a new string with the characters of s in reverse order. Requirements: O(n) time. reverseString('hello') returns 'olleh', and the empty string returns ''.
function reverseString(s) {
// your code here
}
Write the implementation.
Split into characters, reverse, and join: s.split('').join after .reverse(), or [...s].reverse().join(''). The spread form handles multi-byte code points better than split(''). A manual loop building the result from the last index down also works in O(n) time and returns '' for the empty string.
- ✗Calling
reverseon the string directly — only arrays havereverse - ✗Using
split('')and assuming it handles surrogate pairs and emoji correctly - ✗Forgetting that strings are immutable, so a new string must be returned
- →Why does
[...s]split surrogate pairs more correctly thans.split('')? - →How would you reverse the words in a sentence but not the letters?
Solution
Split the string into an array of characters, reverse it, and join it back.
function reverseString(s) {
return [...s].reverse().join('');
}
How it works
Strings in JavaScript are immutable, so you cannot reverse one in place — you must return a new string. The spread [...s] produces an array of characters (handling surrogate pairs correctly), Array.prototype.reverse flips its elements, and join('') glues them back into a string.
Each character is processed a constant number of times, giving O(n) time. The empty string yields an empty array, which reverses to ''. </content> </invoke>