Reverse String

In-place reversal of a character array using converging two pointers.

Easy
Time O(n) Space O(1)
LeetCode
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#

Reverse String
class Solution {
public:
void reverseString(vector<char>& s) {
int l = 0, r = s.size() - 1;
while (l < r) {
swap(s[l++], s[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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.