4. Reverse String
Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory.
Examples:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]Problem Breakdown:
- We use a two-pointer approach. We initialize a left pointer at the beginning (index 0) and a right pointer at the end (last index) of the array.
left = 0 right = len(s) - 1- We loop while the left pointer is less than the right pointer. This ensures we process each pair of characters only once and stop when the pointers meet in the middle.
while left < right:- Inside the loop, we swap the characters at the left and right positions. Python allows us to do this elegantly in one line using tuple unpacking.
s[left], s[right] = s[right], s[left]- After the swap, we move both pointers inward - increment left and decrement right - to process the next pair of characters.
left += 1 right -= 1
Summary:
Use two pointers starting from opposite ends of the array. Swap the characters at each pointer, then move both pointers toward the center. This reverses the array in-place without using extra space. The process continues until the pointers meet in the middle.
Time and Space Complexity:
Time Complexity: O(n) - we process each character once, where n is the length of the string.
Space Complexity: O(1) - we only use two pointer variables regardless of input size.
Python Solution:
def reverseString(s):
left = 0
right = len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1JavaScript Solution:
var reverseString = function(s) {
let left = 0;
let right = s.length - 1;
while (left < right) {
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
};Java Solution:
class Solution {
public void reverseString(char[] s) {
int left = 0;
int right = s.length - 1;
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}