Reverse String(#344)
Category: String, Two Pointer
๐งฉ Problem Statement
Write a function that reverses a character array in-place. You must do this by modifying the input array directly with O(1) extra memory.
๐ Examples
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
๐ง Approach
Approach โ Two Pointer In-place:**
We solve this using the two-pointer approach. Initialize one pointer at the start (`left = 0`) and the other at the end (`right = s.length - 1`). Swap the characters at these positions and move the pointers toward each other until they meet. This approach reverses the array in-place without using extra space.
**Note:** A brute force method using a new array is possible, but it violates the problem constraint of O(1) extra space.
๐ป Code
// ๐น Two Pointer In-place Reversal
var reverseString = function(s) {
let left = 0, right = s.length - 1;
while (left < right) {
[s[left], s[right]] = [s[right], s[left]]; // Swap using destructuring
left++;
right--;
}
};
๐ Complexity
Time: O(n)
Space: O(1)