Reverse String
Easy
📘 Problem Statement
Write a function that reverses a string. The input string is given as an array of characters. You must do this by modifying the input array in-place with \(O(1)\) extra memory.
🔍 Example
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
🛠️ Solution
The problem imposes a constraint that you need to reverse the string in-place
. This means you cannot use another array or routines such as reversed()
or slicing like s[::-1]
which actually creates a new list and does not do in-place reverse.
For in-place string reversal we will use Two Pointer
approach, where we will have two pointers:
left
intially pointing to the start of the array andright
which will be initiallized to point to the end of the array.
Now we will iterate throught the array and in each iteration we will :
- swap values of left and right
- increase left by 1 and decrease right by 1.
- continue to iterate as long as left < right.
def reverseString(s):
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
🕒 Time Complexity: \(O(n)\)
📦 Space Complexity: \(O(1)\)