Reverse String

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

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:

Contents

Solution 1 - Swap characters from both sides using two pointers

In this approach, we will use two pointers to point to both ends of input string s and swap characters.

Implementation steps:
  • Create two pointer variables i and j to point to left and right ends of input string s characters.
  • Then, run a while loop until i and i don't intersect with each other, then swap the characters at these indexes, and increment left pointer i and decrement right pointer j.
Java
import java.util.Arrays;

public class ReverseString {

    static void reverseString(char[] s) {
        int i = 0;
        int j = s.length-1;
        while(i<j) {
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
            i++;
            j--;
        }
    }

    public static void main(String[] args) {
        char[] s = new char[]{'h', 'e', 'l', 'l', 'o'};
        reverseString(s);
        System.out.println(Arrays.toString(s));
        s = new char[]{'H', 'a', 'n', 'n', 'a', 'h'};
        reverseString(s);
        System.out.println(Arrays.toString(s));
    }
}
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of the input array s.
Space complexity: O(1).

Above implementations source code can be found at GitHub link for Java code