Reverse String
Swap characters from both ends moving inward until they meet O(n) time, O(1) space.
Problem Statement
You are given a string s. Reverse it in place.
Don't use extra space (no new string, no .reverse()).
Brute Force
Build a new reversed string, then copy each character back into s. It
works, but it uses extra space — which we're not allowed to use.
function reverseString(s) {const temp = [...s].reverse();for (let i = 0; i < s.length; i++) {s[i] = temp[i];}}
Time: O(n) Space: O(n) — this extra space is what we want to avoid.
Better Approach: Two Pointers
Put one pointer at the start of the string, one at the end. Swap the characters they point to, then move both pointers inward. Stop when they meet in the middle.
function reverseString(s) {let left = 0;let right = s.length - 1;while (left < right) {[s[left], s[right]] = [s[right], s[left]];left++;right--;}}
Complexity
We touch each character once.
Only two pointers used, no matter how long the string is.
Using .reverse() or building a new string gives the right answer, but it
breaks the O(1) space rule. Interviewers want to see the swap logic, not the
shortcut.
How to Explain It in an Interview
How to Explain it in an Interview
It's the same idea either way — two pointers is just the common name for it. What matters is showing you're swapping in place, not creating a new string.
The middle character just stays put — the loop stops before the pointers reach it.