Reverse String [Easy] — Two Pointers In-Place Swap
Advertisement
Problem Statement
Write a function that reverses a string. The input is given as an array of characters s. Must do it in-place with O(1) extra memory.
Input: ["h","e","l","l","o"] → Output: ["o","l","l","e","h"]
Intuition
Two pointers from both ends, swap and move inward until they meet.
Solutions
C
void reverseString(char* s, int n) {
int l=0, r=n-1;
while (l<r) { char t=s[l]; s[l++]=s[r]; s[r--]=t; }
}
C++
void reverseString(vector<char>& s) {
int l=0, r=s.size()-1;
while (l<r) swap(s[l++],s[r--]);
}
Java
public void reverseString(char[] s) {
int l=0, r=s.length-1;
while (l<r) { char t=s[l]; s[l++]=s[r]; s[r--]=t; }
}
JavaScript
var reverseString = function(s) {
let l=0, r=s.length-1;
while (l<r) { [s[l],s[r]]=[s[r],s[l]]; l++; r--; }
};
Python
def reverseString(s: list[str]) -> None:
l, r = 0, len(s)-1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1; r -= 1
Complexity
- Time: O(n)
- Space: O(1)
Advertisement