Reverse the array of characters s in-place using O(1) extra memory.

Pattern: Two Pointers · Template: Arrays & Strings

Examples

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"]

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is a printable ASCII character

Common Approaches

Typical techniques for this pattern:

Approach Time Space Notes
Opposite ends (this problem) O(n) O(1) Sorted array pair search, reversal
Slow / fast pointers O(n) O(1) Linked list middle, cycle detection
Same-direction chase O(n) O(1) Remove duplicates in-place
Sliding window (variable) O(n) O(1) Subarray with constraint

Thinking Process

In-place reversal is a classic two-pointer pattern: swap the characters at the ends, then move inward until the pointers meet.

  • left starts at 0, right at n - 1
  • While left < right, swap s[left] and s[right], then increment left and decrement right
  • No extra array needed — each swap fixes two positions
Two pointers 1 3 5 7 9 L R move L/R based on comparison

Solution — O(n) time, O(1) space

class Solution {
public:
    void reverseString(vector<char>& s) {
        int left = 0, right = (int)s.size() - 1;
        while (left < right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            ++left;
            --right;
        }
    }
};

Solution Explanation

Approach: Opposite ends (this problem)

Key idea: In-place reversal is a classic two-pointer pattern: swap the characters at the ends, then move inward until the pointers meet.

How the code works:

  • left starts at 0, right at n - 1
  • While left < right, swap s[left] and s[right], then increment left and decrement right
  • No extra array needed — each swap fixes two positions

Walkthrough — input s = ["h","e","l","l","o"], expected output ["o","l","l","e","h"]:

  1. Initialize variables from the problem setup.
  2. Apply the main loop / recursion until the condition is met.
  3. Confirm the result matches the expected output.

Time: O(n) · Space: O(1)

Common Mistakes

  • Using left <= right and swapping the middle element twice (use left < right)
  • Allocating a second array — violates the in-place constraint
  • Forgetting that s is modified in place (return type is void)

Key Takeaways

References

Template Reference