Reverse String (LeetCode 344): Solution and Explanation
You are given a string as an array of characters. Reverse the order of the characters inside that same array, using only a constant amount of extra memory, and return nothing.
Watch it run step by step
Try your own input and write the code →Intuition
If memory were free, you could build a new array by reading the input from the back to the front and then copy it over the original. That is linear time, but it needs a second array as large as the input, and the problem explicitly asks for constant extra space.
Think about where each character needs to end up. The first character goes to the last position, the second to the second to last, and in general index i trades places with index n - 1 - i. These moves come in pairs: if you swap position 0 with position n - 1, both characters are now in their final places in one step. That means you never need to store more than one character at a time.
Two pointers express this cleanly. Put left at the start and right at the end, swap the characters they point to, then move both pointers one step toward the middle. Each swap finishes two positions, so after about n / 2 swaps every character is where it belongs.
The loop stops when the pointers meet or cross. For an odd length, the middle character is its own mirror and simply stays put; for an even length, the pointers cross right after the last pair is swapped. The condition left < right handles both cases without any special code. This same converging-pointer pattern shows up in palindrome checks, reversing parts of arrays, and the classic array rotation trick.
Approach: Two pointers swapping toward the middle
- Set
left = 0andright = len(s) - 1, the first and last indices. - While
left < right, swaps[left]ands[right]using tuple assignment. - Move
leftone step right andrightone step left. - When the pointers meet or cross, every pair has been swapped and the array is reversed in place.
- Return nothing, because the caller reads the modified array directly.
Step-by-step example
s = [h,e,l,l,o]
- Start with
left = 0pointing at h andright = 4pointing at o. - Swap them, giving [o,e,l,l,h]. Move to
left = 1andright = 3. - Swap e and l, giving [o,l,l,e,h]. Move to
left = 2andright = 2. - Now
leftequalsright, so the loop stops. The middle l was already in place. - The array reads [o,l,l,e,h], which is hello reversed.
Code: Python, Java, C++
1class Solution:
2 def reverseString(self, s: List[str]) -> None:
3 left, right = 0, len(s) - 1
4
5 while left < right:
6 s[left], s[right] = s[right], s[left]
7 left += 1
8 right -= 11class Solution {
2 public void reverseString(char[] s) {
3 int left = 0, right = s.length - 1;
4
5 while (left < right) {
6 char temp = s[left];
7 s[left] = s[right];
8 s[right] = temp;
9 left++;
10 right--;
11 }
12 }
13}1class Solution {
2public:
3 void reverseString(vector<char>& s) {
4 int left = 0, right = s.size() - 1;
5
6 while (left < right) {
7 swap(s[left], s[right]);
8 left++;
9 right--;
10 }
11 }
12};Time and space complexity
O(n)
The loop runs about n / 2 times, and each iteration does a single swap and two pointer moves, which is linear overall.
O(1)
Only the two indices are stored. The swap happens within the input array.
Other approaches
Recursive swap (time O(n), space O(n))
Swap the outermost pair, then call the function on the inner range left + 1 to right - 1 until the range is empty. It shows the same idea recursively, but the call stack grows to n / 2 frames, so it does not meet the constant-space requirement.
Built-in reverse (time O(n), space O(1))
Python's s.reverse() reverses a list in place and is perfectly fine in real code. In an interview it usually defeats the purpose of the question, so be ready to write the two pointer loop it hides.
Common mistakes
- Writing
s = s[::-1]. That creates a new list and rebinds the local name, so the caller's array stays unchanged. Uses[:] = s[::-1]if you want a one-liner, though it uses O(n) temporary space. - Looping while
left <= right. It is harmless for this problem, but it performs a pointless self-swap in the middle, and the same habit causes bugs in problems where the middle element matters. - Iterating
iover the whole array and swappings[i]withs[n - 1 - i]. After the halfway point, each pair gets swapped back, and the array ends up unchanged. - Swapping with a temporary in a language like Java or C++ but assigning in the wrong order, which overwrites one character before saving it.
Frequently asked questions
How do you reverse a string in place?
Place one pointer at each end, swap the characters they point to, and move both pointers inward until they meet. Each swap fixes two positions, and only the two indices are stored.
Why doesn't s = s[::-1] work for Reverse String?
Slicing builds a new list and assigning it to s only changes which object the local variable refers to. The judge checks the original list, which was never modified.
What is the time complexity of reversing a string with two pointers?
O(n). The loop does about n / 2 swaps, and each swap is constant time. Space is O(1), since nothing besides the two indices is allocated.