#344
Reverse String
Easy Two pointers
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Reverse a char array in place without making a new array.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: flip the order of characters without making a new array.
Why this works: swapping the two ends fixes two positions at once; move inward until the pointers meet.
Example: ['h','e','l','l','o']
swap 0,4 → o e l l hswap 1,3 → o l l e hl=2, r=2 → stop
✦Hints open one at a time
Swap the first and last characters, then move inward.
Stop when the two indexes meet.
↗Approach
Keep a left index at 0 and a right index at the end, swap, and move both toward the middle. Each swap fixes two positions, so n/2 swaps reverse the array.
</>Solution (Java)
class Solution {
public void reverseString(char[] s) {
int l = 0, r = s.length - 1;
while (l < r) {
char tmp = s[l]; // classic swap with a temp variable
s[l] = s[r];
s[r] = tmp;
l++;
r--;
}
}
}
!Common mistake
Looping over the whole array and swapping every pair twice, which puts everything back where it started.
