Problem
Write a function that reverses a string. The input string is given as an array of characters. You must do this by modifying the input array in-place with O(1) extra memory.
Example
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Solution
Use two pointers — one at the start, one at the end. Swap them and move both pointers toward the middle. Stop when they meet.
def reverse_string(s):
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return s
function reverseString(s) {
let left = 0;
let right = s.length - 1;
while (left < right) {
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
return s;
}
#include <vector>
using namespace std;
void reverseString(vector<char>& s) {
int left = 0, right = s.size() - 1;
while (left < right) {
swap(s[left], s[right]);
left++;
right--;
}
}
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--;
}
}
Complexity
- Time: O(n) — we visit each character once
- Space: O(1) — only two pointer variables, no extra data structures
Why Two Pointers
The two-pointer technique is perfect when you need to process elements from both ends. It avoids creating a copy of the array (which would use O(n) extra space) and finishes in half the iterations of a naive approach.
Comments
Join the discussion. Got a question, found an issue, or want to share your experience?