Reverse String
Reverse an array of characters in place by walking two pointers inward from both ends and swapping as you go - O(n) time, O(1) extra space.
Problem Statement
Write a function that reverses a string. The input string is given as an array
of characters s, and you must modify it in place with O(1) extra
memory - no new array, no built-in .reverse().
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Approach: Two Pointers
The array only needs its front and back halves swapped - there's no reason to touch the middle twice or allocate anything new. Keep one pointer at each end and walk them toward the center, swapping the characters they point at on every step:
Points at the first character that still needs to move toward the end.
Points at the last character that still needs to move toward the front.
Swap s[left] and s[right], then move left forward and right back.
Stop once they meet or cross - at that point every character has been
placed exactly once.
function reverseString(s) {
let left = 0;
let right = s.length - 1;
while (left < right) {
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
}
// In-place - the caller's array is mutated, nothing is returned.
const chars = ["h", "e", "l", "l", "o"];
reverseString(chars);
console.log(chars); // ["o", "l", "l", "e", "h"]Complexity Analysis
Each pointer traverses roughly half the array once - every element is touched exactly one time.
The swap happens on the array the caller already owns via destructuring assignment - no second array, no recursion stack.
Returning a brand-new reversed array ([...s].reverse()) technically produces
the right value, but it violates the in-place, O(1)-space constraint the
problem is actually testing for. If you reach for recursion instead, say so
out loud - it also solves it, but costs O(n) call-stack space, which is
worth mentioning even if the interviewer doesn't ask.
How to Explain it in an Interview
JS strings are immutable, so you can't swap characters in place. You'd
split('') into an array first (O(n) space), reverse it with the same
two-pointer swap, then join('') back - no longer truly O(1) space.
It solves the problem, but in an interview it signals you don't know why it works - walking through the two-pointer swap shows the underlying technique, which is what transfers to harder variants.
Yes - when left === right the loop condition left < right is already
false, so the middle character (which doesn't need to move) is left alone.