Reverse a String In-Place
Solve this Problem
Given a string
s, return it reversed.
The naive approach rebuilds the result one character at a time through string concatenation — correct, but wasteful in languages where strings are immutable, since every append can re-copy everything built so far. The two pointerTwo PointerUsing two indices that move toward (or away from) each other through a structure, instead of a single pass that only moves in one direction. technique avoids that entirely: convert the string to a character array and swap from both ends inward, using no more than a single temporary variable at any moment.
Test Case 1:
Input:s = "hello"
Output:"olleh"
Explanation:Each character ends up at its mirrored position from the other end.
Test Case 2:
Input:s = "a"
Output:"a"
Explanation:A single character has nothing to swap with — it stays put.
Test Case 3:
Input:s = "ab"
Output:"ba"
Explanation:The two characters simply trade places.
Constraints
- ◆
1 ≤ s.length ≤ 10⁵ - ◆
s consists of printable ASCII characters
🚀
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
🧪Try your own test case
| 1 | class Solution { |
| 2 | public String reverseStringInPlace(String s) { |
| 3 | char[] chars = s.toCharArray(); |
| 4 | int left = 0, right = chars.length - 1; |
| 5 | while (left < right) { |
| 6 | char temp = chars[left]; |
| 7 | chars[left] = chars[right]; |
| 8 | chars[right] = temp; |
| 9 | left++; |
| 10 | right--; |
| 11 | } |
| 12 | return new String(chars); |
| 13 | } |
| 14 | } |
| 15 |
h
e
l
l
o
↑left
↑right
Variables
left
0right
4INITIALIZE
Set left to index 0 and right to index 4. Swap the characters they point to, then move both pointers inward.
Step 1 / 6
Approach & Solutions
Brute Force
BruteWalk from the last character to the first, appending each one onto a growing result string. Correct, but in languages with immutable strings (Java, Python), every "+=" allocates a brand-new string and copies everything built so far — so the total work across all n appends adds up to O(n²).
Time
O(n²)Space
O(n)Java
1class Solution {
2 public String reverseStringInPlace(String s) {
3 String result = "";
4 for (int i = s.length() - 1; i >= 0; i--) {
5 result += s.charAt(i);
6 }
7 return result;
8 }
9}Optimal — Two Pointer Swap
OptimalConvert the string to a character array, then swap the character at left with the one at right, moving both pointers inward until they meet. Each swap needs only a single temp variable — no growing copy, no repeated reallocation.
Time
O(n)Space
O(1)Java
1class Solution {
2 public String reverseStringInPlace(String s) {
3 char[] chars = s.toCharArray();
4 int left = 0, right = chars.length - 1;
5 while (left < right) {
6 char temp = chars[left];
7 chars[left] = chars[right];
8 chars[right] = temp;
9 left++;
10 right--;
11 }
12 return new String(chars);
13 }
14}