15% off all plans & roadmaps Use code
See plansReverse String
- LeetCode 344
- Easy
- Two Pointers
- String Reversal
Updated
TL;DR: Reverse the character array in place by swapping the two ends and moving inward. Two pointers finish in O(n) time with O(1) extra space, while a reversed copy would need O(n) space.
Problem
Write a function that reverses a string. The string arrives as an array of characters, s.
Change the array in place. You may use only O(1) extra memory.
Example 1
Input: s = ["h", "e", "l", "l", "o"] Output: ["o", "l", "l", "e", "h"]
Example 2
Input: s = ["H", "a", "n", "n", "a", "h"] Output: ["h", "a", "n", "n", "a", "H"]
Constraints
1 <= s.length <= 10^5s[i]is a printable ASCII character.
Constraints that matter
nup to 10^5 rules out any O(n^2) approach, which could take about 10^10 steps in the worst case.- The
O(1)memory limit rules out building a reversed copy, so every change has to happen insides. - Each slot holds one printable ASCII character, so you swap whole elements and never split characters.
- An odd length leaves one middle element in place, so the loop must stop cleanly when the pointers meet on that element.
Hints
Hint 1
Reversing a string means mirroring it.
Hint 2
The beginner's version builds the answer somewhere else first.
Solution
Intuition
Reversing a string means mirroring it. The first character goes to the last slot, the second goes to the second-to-last slot, and so on. Each index i has one partner, index n - 1 - i, and the two values trade places.
Picture two people at opposite ends of a bench of name cards, swapping their cards and then stepping toward each other. The left person is the left pointer, the right person is the right pointer, and each swap is one mirrored pair.
That partner structure points to the two pointers pattern. Put one index at the left end and one at the right end. Swap the values they point at, then move both indices inward. The next pair to visit is always the next pair inward.
The pointers stop when they meet or cross. By then every mirrored pair has swapped exactly once. The swap needs only one temporary value, so no extra array is required.
Worked example
Input: s = ["H", "a", "n", "n", "a", "h"] Output: ["h", "a", "n", "n", "a", "H"] Explanation: The first and last characters swap, then the second and second-to-last, and so on. The inner pairs are equal, so those swaps change nothing visible. The result is the mirror image of the input.
Approach 1: Brute force with a reversed copy
The beginner's version builds the answer somewhere else first. Read the input from the last index to the first, and append each character to a new list. Then copy the new list back into s.
This version is correct and easy to reason about. It breaks the memory rule, because the new list holds n characters at the same time as the input.
Steps
- Create an empty list
out. - Loop
ifromn - 1down to0and appends[i]toout. - Loop
ifrom0ton - 1and sets[i]toout[i]. - Return nothing. The caller sees the change because
swas modified.
Dry run
Start with s = ["H", "a", "n", "n", "a", "h"]. Reading from the end, out grows as follows.
| i | s[i] | out after append |
|---|---|---|
| 5 | h | [h] |
| 4 | a | [h, a] |
| 3 | n | [h, a, n] |
| 2 | n | [h, a, n, n] |
| 1 | a | [h, a, n, n, a] |
| 0 | H | [h, a, n, n, a, H] |
The copy loop then writes out[0] through out[5] back into s. The array becomes ["h", "a", "n", "n", "a", "H"], which matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the array length. The first loop runs n times, and the second loop runs n times, so the total work is 2n, which is O(n). The list out holds n characters at its peak, so the extra space is O(n). That extra space is exactly what the problem forbids.
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseString(self, s: List[str]) -> None:
"""Do not return anything; modify s in-place instead."""
# Build the reversed characters in a new list
out = []
for i in range(len(s) - 1, -1, -1):
out.append(s[i])
# Copy them back so the caller sees the change
for i in range(len(s)):
s[i] = out[i]JavaTested in our runner
class Solution {
public void reverseString(String[] s) {
int n = s.length;
String[] out = new String[n];
for (int i = 0; i < n; i++) {
out[i] = s[n - 1 - i];
}
for (int i = 0; i < n; i++) {
s[i] = out[i];
}
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
void reverseString(vector<string>& s) {
int n = s.size();
vector<string> out(n);
for (int i = 0; i < n; i++) {
out[i] = s[n - 1 - i];
}
for (int i = 0; i < n; i++) {
s[i] = out[i];
}
}
};JavaScriptTested in our runner
var reverseString = function(s) {
const n = s.length;
const out = new Array(n);
for (let i = 0; i < n; i++) {
out[i] = s[n - 1 - i];
}
for (let i = 0; i < n; i++) {
s[i] = out[i];
}
};GoTested in our runner
func reverseString(s []string) {
n := len(s)
out := make([]string, n)
for i := 0; i < n; i++ {
out[i] = s[n-1-i]
}
copy(s, out)
}C#Tested in our runner
public class Solution {
public void reverseString(string[] s) {
int n = s.Length;
string[] output = new string[n];
for (int i = 0; i < n; i++) {
output[i] = s[n - 1 - i];
}
for (int i = 0; i < n; i++) {
s[i] = output[i];
}
}
}The String Reversal infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
String Reversal
Part of Two Pointers
Approach 2: Two pointers, swap from both endsOptimalString Reversal
What's slow in the copy approach is the second array. Every character is written twice, once into out and once back into s. The insight that fixes it: each character only needs one swap with its mirror partner. Swapping inside s removes the copy entirely.
Place left at index 0 and right at index n - 1. Swap the two values, then move left right and right left. Stop when left is no longer less than right.
The pointers only meet in the middle, so each mirrored pair is swapped exactly once.
Why it is correct. After each step, the outer pairs already hold their final characters, and the unvisited middle keeps its original order. Each index has exactly one mirror partner, so no position is skipped or swapped twice.
Steps
- Set
leftto 0 andrightton - 1. - While
left < right, swaps[left]ands[right]. - Add 1 to
leftand subtract 1 fromright. - When the loop ends,
sholds the reversed characters. Return nothing.
Dry run
Start with s = ["H", "a", "n", "n", "a", "h"], left = 0, and right = 5. The table shows the state at the check at the top of each pass.
| Check | left | right | left < right? | Action | s at this check |
|---|---|---|---|---|---|
| 1 | 0 | 5 | yes | swap H and h | [H, a, n, n, a, h] |
| 2 | 1 | 4 | yes | swap a and a | [h, a, n, n, a, H] |
| 3 | 2 | 3 | yes | swap n and n | [h, a, n, n, a, H] |
| 4 | 3 | 2 | no | stop | [h, a, n, n, a, H] |
The last row shows the loop ends with s equal to the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the array length. The loop body runs once per mirrored pair, which is floor(n / 2) times. Each pass does two reads, two writes and two pointer updates, all constant time, so the total time is O(n). The method keeps two integer indices and a temporary value, and that count does not grow with n, so the space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseString(self, s: List[str]) -> None:
"""Do not return anything; modify s in-place instead."""
left, right = 0, len(s) - 1
# Swap mirrored pairs until the pointers meet or cross
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1JavaTested in our runner
class Solution {
public void reverseString(String[] s) {
int left = 0;
int right = s.length - 1;
// Swap mirrored pairs until the pointers meet
while (left < right) {
String temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
void reverseString(vector<string>& s) {
int left = 0;
int right = (int)s.size() - 1;
// Swap mirrored pairs until the pointers meet
while (left < right) {
swap(s[left], s[right]);
left++;
right--;
}
}
};JavaScriptTested in our runner
var reverseString = function(s) {
let left = 0;
let right = s.length - 1;
// Swap mirrored pairs until the pointers meet
while (left < right) {
const temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
};GoTested in our runner
func reverseString(s []string) {
left, right := 0, len(s)-1
for left < right {
s[left], s[right] = s[right], s[left]
left++
right--
}
}C#Tested in our runner
public class Solution {
public void reverseString(string[] s) {
int left = 0;
int right = s.Length - 1;
while (left < right) {
string temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}Common mistakes
- Looping
while left < ninstead ofwhile left < right. Past the middle, each pair swaps a second time and undoes the first half. Fix: stop when the pointers meet, so each pair swaps once. - Writing
s[left] = s[right]; s[right] = s[left];with no temporary. The second line reads the value the first line already overwrote, so both slots hold the same character. Fix: save one value first, or use a tuple swap in Python. - Writing
s = s[::-1]inside the method in Python. The slice builds a new list, and the namesnow points to it, so the caller's list does not change. Fix: swap elements through their indices.s[:] = s[::-1]also works, but it builds an O(n) copy. - Starting
rightatninstead ofn - 1. The first swap reads one index past the end, which raises an IndexError in Python or an ArrayIndexOutOfBoundsException in Java. Fix: start atlen(s) - 1ors.length - 1. - Reassigning the parameter in Go or C#, for example
s = outin Go. The parameter is a local copy of the slice or array reference, so the caller still sees the old elements. Fix: write into the existing elements with an index loop orcopy.
Edge cases
- Length 1, for example
["a"]. The loop never runs, and the output equals the input. - Length 2, for example
["a", "b"]. One swap gives["b", "a"]. - Odd length, for example
["a", "b", "c"]. The result is["c", "b", "a"], and the middlebstays in place. - All characters equal, for example
["x", "x", "x", "x"]. Each swap changes nothing visible, and the output matches the input. - Palindrome, for example
["r", "a", "c", "e", "c", "a", "r"]. The reversed string equals the original, so the array stays the same. - Maximum length 100000 with space or quote characters. Each character follows the same rule, so the loop does about 50000 swaps with no special cases.
Follow-ups interviewers ask
- What if you must reverse the string recursively?
- Swap the outer pair, then recurse on the inner range. It is correct, but the call depth is n / 2. With n equal to 10^5, Python's default recursion limit of about 1000 fails, and the call stack adds O(n) space. Stay with the iterative loop.
- What if the input is a singly linked list of characters?
- You cannot walk two ends at once, and you cannot step backwards. Reverse the list by relinking pointers with three variables, prev, current and next. That keeps the extra space at O(1), and the time is O(n).
- How would you reverse each word in place inside a sentence?
- Reverse the whole character array first. Then reverse the range of each word again to restore its letters. Each character is touched a fixed number of times, so the total time is O(n) with O(1) extra space.
Reverse String FAQ
What is the time complexity of Reverse String?
The time is O(n), where n is the array length. The loop runs about n / 2 times with constant work each time. Any correct solution must touch every slot, so O(n) is the best possible.
Why use two pointers for Reverse String?
Reversal pairs index i with index n - 1 - i. Two pointers, one at each end, visit exactly those pairs in order. The pointers move inward together, so the work stays linear and the memory stays constant.
Can Reverse String be solved in O(1) extra space?
Yes. The two-pointer solution keeps two integer indices and one temporary value. The reversed-copy approach needs O(n) extra space, so it fails the memory constraint.
Why can't I use s[::-1] in Python for this problem?
The slice creates a new list and rebinds the local name s. The caller's list does not change, and the copy uses O(n) memory. Swap elements through their indices instead.
Can I reverse the characters inside each string in Java or C#?
Not in place. Java and C# strings are immutable, so you cannot change their characters. This problem passes an array of String values, so the solution swaps references between slots. A char array would let you swap the characters directly.
Asked at
See which companies ask this — Pro
Related problems
- Reverse String II · same technique: String Reversal
- Reverse Vowels of a String · same technique: String Reversal
- Reverse Integer · same technique: String Reversal
- Reverse Words in a String · same technique: String Reversal
- Happy Number · same pattern: Two Pointers
- Linked List Cycle · same pattern: Two Pointers
- Remove Duplicates from Sorted Array · same pattern: Two Pointers
- Remove Element · same pattern: Two Pointers
- Merge Strings Alternately · same pattern: Two Pointers
- Move Zeroes · same pattern: Two Pointers