Reverse String
Reverse an array of characters in place using two-pointer recursion from the outer boundaries inward.
01The problem
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 (not counting recursion stack space for the recursive version).
| Input | Output | Why |
|---|---|---|
s = ["h","e","l","l","o"] | ["o","l","l","e","h"] | Array reversed in place |
s = ["H","a","n","n","a","h"] | ["h","a","n","n","a","H"] | Palindromic case reversed |
Constraints: 1 <= s.length <= 10^5, s[i] is a printable ASCII character.
02How to spot it
- The task requires swapping elements symmetrically from the ends towards the center.
- Outer pair: swap
s[0]withs[n - 1]. - Inner problem: reverse
s[1 .. n - 2]. - Notice the self-similar structure: reversing a string of length
nreduces to swapping the outer ends and reversing a string of lengthn - 2.
So: converging two-pointer recursion.
03Pseudocode
reverse(l, r):
if l >= r: return
swap s[l], s[r]
reverse(l + 1, r - 1)- Base case: when left pointer
l >= r, the pointers have met or crossed. Stop. - Swap the outer characters
s[l]ands[r]. - Recurse inward on
(l + 1, r - 1).
04Watch it work
s
Reverse character array in place recursively from ends inward.
Pseudocode
- reverse(l, r):
- if l >= r: return
- swap s[l], s[r]
- reverse(l + 1, r - 1)
Variables
- l
- 0
- r
- 4
05Step-by-step dry run
- 1
s
h0e1l2l3o4lrReverse character array in place recursively from ends inward.
l = 0r = 4
- 2
s
o0e1l2l3h4lrSwap s[0] ('h') with s[4] ('o').
l = 0r = 4left = oright = h
- 3
s
o0e1l2l3h4lrRecurse on inner substring: reverse(1, 3).
nextL = 1nextR = 3
- 4
s
o0l1l2e3h4lrSwap s[1] ('e') with s[3] ('l').
l = 1r = 3left = lright = e
- 5
s
o0l1l2e3h4lrRecurse on inner substring: reverse(2, 2).
nextL = 2nextR = 2
- 6
s
o0l1l2e3h4lrBase case reached: l (2) >= r (2). Inward pointers have met or crossed.
l = 2r = 2
- 7
reversed s
o0l1l2e3h4Array fully reversed: ['o', 'l', 'l', 'e', 'h'].
result = o,l,l,e,h
06Java solution
import java.util.Arrays;
public class ReverseString {
public static void reverseString(char[] s) {
swapEnds(s, 0, s.length - 1);
}
private static void swapEnds(char[] s, int l, int r) {
if (l >= r) return;
char t = s[l];
s[l] = s[r];
s[r] = t;
swapEnds(s, l + 1, r - 1);
}
public static void main(String[] args) {
char[] s1 = {'h', 'e', 'l', 'l', 'o'};
reverseString(s1);
System.out.println(Arrays.toString(s1));
char[] s2 = {'H', 'a', 'n', 'n', 'a', 'h'};
reverseString(s2);
System.out.println(Arrays.toString(s2));
}
}[o, l, l, e, h] [h, a, n, n, a, H]
07Why it works
At each recursion frame, the outermost remaining pair of characters s[l] and s[r] is swapped.
Calling swapEnds(s, l + 1, r - 1) shrinks the unreversed middle section by 2 elements.
When l == r (odd length string, middle character untouched) or l > r (even length string, all pairs swapped), the recursion halts immediately.
08Time and space
- Time complexity:
O(n). There aren / 2recursive calls, each performing anO(1)swap. - Space complexity:
O(n)call stack frames in the recursive version. (In production, an iterative while-loop achievesO(1)space).
09Edge cases
- Single character (e.g.
['a']):l = 0, r = 0 -> l >= rhits base case immediately, no swaps occur. - Two characters (e.g.
['a', 'b']): Swaps once, thenl = 1, r = 0terminates. - Even vs. odd length: Both cleanly handled because
l >= rcoversl == randl == r + 1.
10Common mistakes
- Using
l > rinstead ofl >= ras the base case. For odd-length strings,l == rat the middle character. While swapping a character with itself is harmless, stopping atl >= rprevents an unnecessary recursive call. - Forgetting that
char[]is modified in-place. Do not allocate a new array; mutates[l]ands[r]directly.
11Other approaches
| Approach | Time | Space | Notes |
|---|---|---|---|
| Recursive two-pointer | O(n) | O(n) stack | Illustrates divide-and-conquer shrink |
| Iterative two-pointer | O(n) | O(1) | Standard production implementation |
12In the interview
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. What is the base case condition for reversing a character array recursively?
2. Why is the space complexity of the recursive version O(n) instead of O(1)?
14Solve it yourself
Try implementing recursive string reversal where you return a new String instead of modifying a character array:
return s.charAt(s.length() - 1) + reverse(s.substring(0, s.length() - 1)).- Why is that approach
O(n^2)time in Java due to string immutability?