On this page

Reverse String

6 min read•Two-Pointer Warm-Up
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()).

Example 1:
Input: s = "hello"
Output: "olleh"
Explanation: The string gets flipped end to end.
Example 2:
Input: s = "Hannah"
Output: "hannaH"
Explanation: Same idea, just a longer word.

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

Time: O(n)

We touch each character once.

Space: O(1)

Only two pointers used, no matter how long the string is.

Common Mistake

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

The 30-Second Spoken Pitch
"I use two pointers — one at the start, one at the end. I swap the characters they point to, then move both pointers toward the middle. I stop when they meet. This touches every character once, so it's O(n) time, and I'm not using any extra space, so it's O(1)."
If the Interviewer Probes Deeper:
Why mention two pointers instead of just a loop?

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.

What about odd-length strings?

The middle character just stays put — the loop stops before the pointers reach it.

Next TopicReverse Words in a String