Problem. Reverse a string in place. Because Java String is immutable, the canonical form takes a char[] (this is exactly LeetCode 344's signature) and reverses it with O(1) extra space.
Brute force — O(n) time, O(n) space
Build a new sequence backward:
String reverseNaive(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = s.length() - 1; i >= 0; i--) sb.append(s.charAt(i));
return sb.toString();
}
Correct and readable, but it allocates a second buffer — O(n) space. It also isn't "in place," which is the point of the question.
Optimal — O(n) time, O(1) space
Two pointers from both ends, swapping inward until they meet:
void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while (left < right) {
char tmp = s[left];
s[left] = s[right];
s[right] = tmp;
left++;
right--;
}
}
Each swap fixes two characters and the pointers cover the array once — n/2 swaps, O(n) time, O(1) extra space. The left < right guard correctly handles both even length (pointers cross) and odd length (the middle character is its own mirror and needs no swap).