Reverse a String
EasyWrite a function that reverses a string in place. 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 | Output |
|---|---|
| s = ["h","e","l","l","o"] | ["o","l","l","e","h"] |
| s = ["H","a","n","n","a","h"] | ["h","a","n","n","a","H"] |
Python Solution
def reverse_string(s: list[str]) -> None:
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1JavaScript Solution
function reverseString(s) {
let left = 0, right = s.length - 1;
while (left < right) {
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
}Step-by-Step Explanation
- Use two pointers: one at the start, one at the end.
- Swap the characters at both pointers.
- Move left pointer forward and right pointer backward.
- Stop when the pointers meet or cross.
Complexity Analysis
| Time | O(n) |
| Space | O(1) |
Tags
StringTwo Pointers
Related Problems
Related Tools
All Problems
Two SumPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix