Home
DSA Patterns
Two Pointers
Reverse String
Reverse String
Reverse an array of characters in place with two pointers that swap the ends and walk toward the middle.
Problem Understanding
Reverse String: reverse an array of characters in place, using O(1) extra memory.
Example: ["h", "e", "l", "l", "o"] becomes ["o", "l", "l", "e", "h"].
The Intuition: Mirror Pairs
Reversing sends the character at index i to index n − 1 − i. Those two positions simply trade places, so reversing is just swapping mirror pairs.
The classic two pointers loop walks the pairs from the outside in:
lat the start,rat the end.- Swap
s[l]ands[r]; movelright andrleft. - Stop when they meet or cross.
Every character is touched once and no extra array is needed. The same swap loop reverses each block in Rotate Array.
Interactive Walkthrough
Each step swaps one mirror pair, shown filled; pairs already swapped are shaded because they are final. Try an odd and an even length to see when the pointers meet versus cross.
Dry Run Table
Input: [h, e, l, l, o]
| l | r | Swap | Array |
|---|---|---|---|
| 0 | 4 | h ↔ o | o, e, l, l, h |
| 1 | 3 | e ↔ l | o, l, l, e, h |
| 2 | 2 | stop | o, l, l, e, h |
The Solution Template
Swap the ends, walk inward.
Reverse String Code
1var reverseString = function(s) {2 let l = 0, r = s.length - 1;3 while (l < r) {4 [s[l], s[r]] = [s[r], s[l]];5 l++;6 r--;7 }8};
Edge Cases & Common Mistakes
- One character: l and r start equal; nothing to do.
- Looping while l <= r: harmless, but swaps the middle character with itself.
- Looping to n instead of n / 2: every pair is swapped twice and the array ends up unchanged.
- Building a new string: uses O(n) memory; the problem asks for in place.
Summary
Reversing swaps each character with its mirror. Start l and r at the ends, swap, move both inward, and stop when they meet. O(n) time, O(1) space.
More practice: DSA interview questions with answers · patterns cheat sheet
