Problem
Given an array of characters, reverse it in-place using O(1) extra memory โ you cannot allocate a new array to hold the result. The modification must happen directly on the input array.
- Input:
s = ["h","e","l","l","o"] - Output:
["o","l","l","e","h"] - Explanation: Characters are swapped from both ends toward the center until the whole array is reversed.
Intuition
The key constraint is that no extra array is allowed, so we need to rearrange characters in the original array. Placing a pointer at each end and swapping inward achieves this in one pass โ by the time the two pointers meet in the middle, every character has been moved to its correct reversed position.
Solution โ Two Pointers
Place one pointer at the start and one at the end. Swap the characters they point to, then advance both pointers toward the center. Stop when they meet or cross.
- Initialize
left = 0andright = len(s) - 1. - While
left < right:- Swap
s[left]ands[right]. - Increment
left; decrementright.
- Swap
- The array is now reversed in-place.
1def reverseString(s: list[str]) -> None:
2 left, right = 0, len(s) - 1
3 while left < right:
4 s[left], s[right] = s[right], s[left] # swap without a temp variable
5 left += 1
6 right -= 1Time: O(n) โ each character is visited exactly once.
Space: O(1) โ only two index variables; no auxiliary storage.
Complexity Summary
| Approach | Time | Space | When to use |
|---|---|---|---|
| Two Pointers (in-place) | O(n) | O(1) | Any time in-place reversal is required |
Common Mistakes
- Using
s[::-1]in Python โ this creates a brand-new list rather than modifying the existing array, which violates the O(1) space constraint and won't update the caller's array. - Returning a value instead of modifying in-place โ the function signature is
void; returning a reversed copy gets the right output but misses the point of the problem. - Using
left <= rightas the loop condition โ when the array has an odd length, the middle element gets swapped with itself (harmless, but unnecessary);left < rightis the correct and cleaner termination. - Allocating a temporary
char[]orlistfor the swap โ a simple three-variable swap or Python's simultaneous assignment is all that's needed.
Related Problems
valid-palindromeโ uses the same two-pointer-from-both-ends pattern to compare charactersreverse-linked-listโ the same reversal idea applied to a linked list with pointer manipulationtwo-sum-ii-input-array-is-sortedโ two pointers converging from both ends to find a target sumsquares-of-a-sorted-arrayโ two pointers from both ends merging into a result arrayreverse-words-in-a-stringโ a multi-step reversal that builds on this exact primitive