Reverse String
Problem
Reverse a string in place. The input is given as an array of characters; modify it directly using O(1) extra memory.
s = ["h","e","l","l","o"]["o","l","l","e","h"]def reverse_string(s):
l, r = 0, len(s) - 1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
function reverseString(s) {
let l = 0, r = s.length - 1;
while (l < r) {
[s[l], s[r]] = [s[r], s[l]];
l++;
r--;
}
}
class Solution {
public void reverseString(char[] s) {
int l = 0, r = s.length - 1;
while (l < r) {
char t = s[l]; s[l] = s[r]; s[r] = t;
l++; r--;
}
}
}
void reverseString(vector<char>& s) {
int l = 0, r = s.size() - 1;
while (l < r) {
swap(s[l], s[r]);
l++; r--;
}
}
Explanation
To reverse the array in place without any extra storage, we use the classic two-pointer technique: one pointer at the front and one at the back, swapping their values and walking toward the middle.
Pointer l starts at index 0 and r at the last index. We swap s[l] with s[r], then do l += 1 and r -= 1. Each swap puts two characters into their final mirrored positions at once.
The loop runs while l < r. Once they meet (or cross), every pair has been swapped and the array is fully reversed. A middle character in an odd-length array simply stays where it is.
This uses only O(1) extra memory and a single pass, since each character is touched just once.
Example: ["h","e","l","l","o"]. Swap index 0 and 4 → o...h; swap index 1 and 3 → l and l (no visible change); the middle l stays. Result: ["o","l","l","e","h"].