Leetcode Problem “344. 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.
Example:
Input: s = ["h", "e", "l", "l", "o"]
Output: ["o", "l", "l", "e", "h"]
Assuming:
The problem requires reversing the string in place, thus the two-pointer technique will be effective here:
left
and right
pointers.left
pointer towards the center of the array (increment it) and the right
pointer towards the center of the array (decrement it).left
pointer is greater than or equal to the right
pointer.The algorithm runs in O(N) time, where N is the number of characters in the string, because we are essentially swapping half the elements with the other half.
The space complexity is O(1) as we are not utilizing any extra data structures that grow with the input size.
Here’s the implementation of the strategy in C++:
#include <vector>
#include <iostream>
class Solution {
public:
void reverseString(std::vector<char>& s) {
int left = 0;
int right = s.size() - 1;
while(left < right) {
std::swap(s[left], s[right]);
left++;
right--;
}
}
};
int main() {
Solution solution;
std::vector<char> s = {'h', 'e', 'l', 'l', 'o'};
std::cout << "Original string: ";
for (char c : s) {
std::cout << c;
}
std::cout << std::endl;
solution.reverseString(s);
std::cout << "Reversed string: ";
for (char c : s) {
std::cout << c;
}
std::cout << std::endl;
return 0;
}
left
is initialized to 0 (beginning of the array).right
is initialized to s.size() - 1
(end of the array).left
is less than right
.left
and right
are swapped.left
pointer is incremented by one.right
pointer is decremented by one.left
is no longer less than right
, meaning the string has been reversed.This code effectively reverses the input string in place with constant extra space, meeting the problem’s requirements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?