Suppose we have an array of characters. We have to reverse the string without using any additional space. So if the string is like [‘H’, ‘E’, ‘L’, ‘L’, ‘O’], the output will be [‘O’, ‘L’, ‘L’, ‘E’, ‘H’]
To solve this, we will follow these steps −
- Take two pointers to start = 0 and end = length of the string – 1
- swap first and last characters
- increase start by 1 and decrease-end by 1
Example
Let us see the following implementation to get a better understanding −
class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ start = 0 end = len(s)-1 while start<end: s[start],s[end] = s[end],s[start] start+=1 end-=1string_1 = ["H","E","L","L","O"] ob1 = Solution() ob1.reverseString(string_1) print(string_1)
Input
String = ["H","E","L","L","O"]
Output
["O","L","L","E","H"]