Statement▼
You are given a character array, s
, representing a string. Write a function that reverses the array in-place.
The reversal must be done by modifying the original array directly.
You cannot use extra memory beyond a constant amount
O(1) .
Constraints
1 <= s.length
<= 1000 Each
s[i]
is a printable ASCII character.
Solution
As the input is given as a character array, the problem can be solved efficiently by reversing the array in place without using extra space for another array. The key idea is that reversing means swapping the first character with the last, the second with the second-last, and so on, until all characters are placed in the correct reversed order.
To achieve this, we can use the two pointer technique: one pointer starts at the beginning of the array and the other at the end. We swap the characters at each step at these two positions, then move the pointers closer toward the center. This continues until the pointers meet or cross, ensuring all characters are reversed.
The steps of the algorithm are as follows:
Initialize two pointers:
left
at the start, andright
at the end of the array.While
left < right
:Swap the characters at
s[left]
ands[right]
.Increment
left
by 1 and decrementright
by 1 to move the pointers inward.
The process terminates once the
left
andright
pointers meet simultaneously.
Let’s look at the following illustration to get a better understanding of the solution: