Reverse String
Write a function that reverses an array of characters in place . Use two pointers starting at the left and right ends of the array, swapping the characters they point to and converging toward the middle until they meet.
Constraints
- 1 ≤ s.length ≤ 105
- si is a printable ASCII character
Example
Input
s = ['h', 'e', 'l', 'l', 'o']Output
['o', 'l', 'l', 'e', 'h']Explanation Swapping characters from both ends inward reverses the array to "olleh".
In plain terms
- In place
- Making the change directly inside the given array instead of building a new one, using little to no extra memory.
Swap from both ends, converge toward the middle
0h
1e
2l
3l
4o
Statusinit
left=0 ('h') and right=4 ('o') are about to swap.
What happens in this step
left = 0 (value 'h'), right = 4 (value 'o') The values at the two ends are about to be swapped.
Step 1 of 4
Steps to visualize
- Place one pointer at the start and one at the end of the array.
- Swap the characters at the two pointers.
- Move the left pointer right and the right pointer left.
- Repeat until the pointers meet or cross.
- The array is now reversed in place.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
0h
1e
2l
3l
4o
Statusinit
left=0 ('h') and right=4 ('o') are about to swap.
What happens in this step
left = 0 (value 'h'), right = 4 (value 'o') The values at the two ends are about to be swapped.
Step 1 of 4
Solution
function reverseString(s) {
let left = 0;
let right = s.length - 1;
while (left < right) {
const temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
return s;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
s = ['h', 'e', 'l', 'l', 'o'] | ['o', 'l', 'l', 'e', 'h'] | example from the docstring |
s = ['a'] | ['a'] | smallest valid input, a single character |
s = ['a', 'b', 'c', 'd'] | ['d', 'c', 'b', 'a'] | even-length array, no middle character |
s = ['a', 'b'] | ['b', 'a'] | boundary case, exactly two elements |
s = ['x', 'x'] | ['x', 'x'] | identical characters, no visible change after reversing |
s = ['a', 'b', 'c'] | ['c', 'b', 'a'] | odd-length array with a middle character left untouched |