← Back to DSA Animator
Reverse String LC #344 Easy Two Pointers · In-Place
Problem

Write a function that reverses a string. The input is given as an array of characters s. You must do this in-place with O(1) extra memory — you cannot create a new array.

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"]
Explanation: Two pointers from both ends, swap and move inward.
Constraints: 1 ≤ s.length ≤ 10⁵ | s[i] is a printable ASCII character
Try Examples
Custom:
Approach
Two pointers — swap from both ends, move inward until l ≥ r
No extra array needed. Each swap places two elements in their final position. Exactly ⌊n/2⌋ swaps required. O(n) time, O(1) space.
Character Array
l (left pointer)
r (right pointer)
Swap Operation
s[l]
s[r]
0 swaps
Variables
l
0
r
l<r?
tmp
swaps
0
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init l = 0 (left pointer), r = n−1 (right pointer)
2
While l < r: the two pointers haven't crossed yet
3
Swap s[l]s[r] using a temporary variable
4
Move inward: l++, r--
5
When l ≥ r, all elements are in their final position
Time
O(n)
Space
O(1)
Why This Works

Classic in-place reversal with two pointers. Each swap permanently places two characters in their final positions. After ⌊n/2⌋ swaps, every element is in its correct reversed position. The middle element (odd-length arrays) needs no swap. No extra memory is used beyond a single tmp variable.