Reverse String in-place with O(1) extra memory

Problem Statement: 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. (LeetCode 344) Solution: So the approach I have applied in this problem is very very simple. We initialize a pointer start with 0 and another pointer end with ch.length-1, the start pointer points to first position of the array at the beginning and the end pointer points to the end of the array at the beginning . We swap the elements at start position with the element at end position and then we do start++ and end-- to move the start pointer to the next position and end pointer to the previous position (the second last position in the second iteration, third last in the third iteration and so on). We continue iteration until the condition (start <= end) fails. This simply reverse the array with character elements. Time Complexity : O(n) Space Complexity: O(1) Below is the Java Code for the following problem: public static void reverse(char []ch)   {     int start = 0;     int end = ch.length-1;     while(start <= end)     {       char temp = ch[start];       ch[start] = ch[end];       ch[end] = temp;       start ++;       end --;     } }

To view or add a comment, sign in

Explore content categories