Reverse String

Write a function that reverses a character array in-place. You must do this with O(1) extra memory.

Example 1
Input: ["h","e","l","l","o"] → Output: ["o","l","l","e","h"]
Example 2
Input: ["H","a","n","n","a","h"] → Output: ["h","a","n","n","a","H"]

Solution Approach

Classic two-pointer swap: pointers at both ends, swap and move inward.

  • lo=0, hi=s.length-1.
  • While lo
Java
class Solution {
    public void reverseString(char[] s) {
        int lo = 0, hi = s.length - 1;
        while (lo < hi) {
            char tmp = s[lo]; s[lo] = s[hi]; s[hi] = tmp;
            lo++; hi--;
        }
    }
}
  • Time Complexity: O(N)
  • Space Complexity: O(1)