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:

  • 1 <= s.length <= 105

  • s[i] is a printable ascii character.

My Solution

We can use the two pointer technique. One pointer i is placed at the beginning of the array. The other pointer j is placed and the end of the array. We then swap the characters at the two pointers, increment i and decrement j.

Time complexity would be O(n) because we scan the array once. Space complexity is O(1) because we only use constant extra space.

class Solution {
    public void reverseString(char[] s) {
        int i = 0;
        int j = s.length-1;

        while (i < j) {
            char c = s[i];
            s[i] = s[j];
            s[j] = c;

            i++;
            j--;
        }
    }
}
Previous
Previous

Reverse Vowels of a String

Next
Next

Power of Four