Reverse String
In-place reversal of a character array using converging two pointers.
2 min read
two-pointers string
Problem#
Reverse a vector<char> in place, O(1) extra memory.
Examples#
["h","e","l","l","o"]→["o","l","l","e","h"]["H","a","n","n","a","h"]→["h","a","n","n","a","H"]
Constraints#
1 <= s.length <= 10^5, ASCII.
Approach#
Swap symmetric positions until pointers meet. The library std::reverse is the production answer, but the manual loop is the canonical interview demo.
Solution#
class Solution {public: void reverseString(vector<char>& s) { int l = 0, r = s.size() - 1; while (l < r) { swap(s[l++], s[r--]); } }};func reverseString(s []byte) { l, r := 0, len(s)-1 for l < r { s[l], s[r] = s[r], s[l] l++ r-- }}from typing import List
class Solution: def reverseString(self, s: List[str]) -> None: l, r = 0, len(s) - 1 while l < r: s[l], s[r] = s[r], s[l] l += 1 r -= 1function reverseString(s) { let l = 0, r = s.length - 1; while (l < r) { [s[l], s[r]] = [s[r], s[l]]; l++; r--; }}class Solution { public void reverseString(char[] s) { int l = 0, r = s.length - 1; while (l < r) { char tmp = s[l]; s[l++] = s[r]; s[r--] = tmp; } }}function reverseString(s: string[]): void { let l = 0, r = s.length - 1; while (l < r) { [s[l], s[r]] = [s[r], s[l]]; l++; r--; }}Editorial#
This is the smallest non-trivial two-pointer pattern. Each character is moved at most once and the loop performs exactly n/2 swaps. Worth memorizing as a primitive: many harder problems (reverse-each-word, rotate, palindrome check) build on it.
Complexity#
- Time: O(n).
- Space: O(1).
Concept revision#
Related#