The problem. You're given a string as an array of characters, s. Reverse it in place: change the array itself, using only O(1) extra memory. Nothing is returned.
s = ["h","e","l","l","o"] -> ["o","l","l","e","h"]
s = ["H","a","n","n","a","h"] -> ["h","a","n","n","a","H"]Many string questions are about the string's two ends — reversing it, checking it reads the same both ways, comparing a character with its mirror. The two-pointer pattern puts one index at the start and one at the end, does something with the pair, and moves them towards each other until they meet. That visits each character at most once: O(n) time and O(1) extra space.
It's the first pattern because it's the simplest, and because it works on strings exactly as on arrays. The only string-specific part is the one from the immutability lesson: to change characters in place you need them in an array — which this problem hands you already.
Copy the characters, then write the copy back from the last character to the first. Simple, but the copy breaks the O(1)-memory rule.
function reverseString(s) { const copy = [...s]; // O(n) extra memory for (let i = 0; i < s.length; i++) { s[i] = copy[s.length - 1 - i]; // read the copy back to front }}Time O(n), space O(n). One pass to copy, one to write back — but the copy is as big as the input.
Swap the first and last characters, then the second and second-to-last, and so on. Each swap puts two characters in their final places, and nothing has to be stored except the two indexes.
Each swap fixes two characters; the pointers meet in the middle.
function reverseString(s) { let left = 0, right = s.length - 1; while (left < right) { [s[left], s[right]] = [s[right], s[left]]; // swap the two ends left++; // then move both inwards right--; }}Time O(n), space O(1). n / 2 swaps. With an odd length the middle character is never touched — it's already in place.
Same speed, but only the two-pointer version meets the in-place requirement. Every language also has a built-in (s.reverse(), s.reverse(), Collections.reverse, std::reverse) that does exactly this swap loop.
< is the condition to remember.