344. Reverse String
Problem Description
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.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Constraints:
1 <= s.length <= 10⁵s[i]is a printable ascii character
Solution
Python Solution
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
Time Complexity: O(n)
Where n is the length of the string.
Space Complexity: O(1)
Only uses two pointers regardless of input size.
Java Solution
class Solution {
public void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
Time Complexity: O(n)
Where n is the length of the string.
Space Complexity: O(1)
Only uses two pointers and a temporary variable.
C++ Solution
class Solution {
public:
void reverseString(vector& s) {
int left = 0, right = s.size() - 1;
while (left < right) {
swap(s[left], s[right]);
left++;
right--;
}
}
};
Time Complexity: O(n)
Where n is the length of the string.
Space Complexity: O(1)
Only uses two pointers and swap is in-place.
JavaScript Solution
/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
var reverseString = function(s) {
let left = 0, right = s.length - 1;
while (left < right) {
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
};
Time Complexity: O(n)
Where n is the length of the string.
Space Complexity: O(1)
Only uses two pointers and destructuring assignment.
C# Solution
public class Solution {
public void ReverseString(char[] s) {
int left = 0, right = s.Length - 1;
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
Time Complexity: O(n)
Where n is the length of the string.
Space Complexity: O(1)
Only uses two pointers and a temporary variable.
Approach Explanation
The solution uses the two-pointer technique:
- Key Insight:
- In-place reversal
- Two pointers
- Swap operation
- Memory constraint
- Algorithm Steps:
- Initialize pointers
- Swap characters
- Move pointers
- Stop at middle
Example walkthrough:
- Set pointers
- Swap elements
- Update pointers
- Check condition
Optimization insights:
- No extra space
- Single pass
- Efficient swaps
- Early stopping
Edge Cases:
- Empty string
- Single character
- Even length
- Odd length