The task is to 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.
s
?
def reverseString(s: List[str]) -> None:
To reverse the string in-place with O(1) extra space:
Here’s how you can implement this in Python:
from typing import List
def reverseString(s: List[str]) -> None:
left, right = 0, len(s) - 1
while left < right:
# Swap characters
s[left], s[right] = s[right], s[left]
# Move pointers
left, right = left + 1, right - 1
left
pointer to the start (0th index).right
pointer to the end (last index).left
and right
.left
and decrement right
.left
is no longer less than right
.Consider s = ["h", "e", "l", "l", "o"]
:
left = 0, right = 4
["h", "e", "l", "l", "o"]
Swap s[0] and s[4]:
["o", "e", "l", "l", "h"]
Move pointers: left = 1, right = 3
Swap s[1] and s[3]:
["o", "l", "l", "e", "h"]
Move pointers: left = 2, right = 2
Since left is not less than right, stop
Final state: ["o", "l", "l", "e", "h"]
The elements are now reversed in-place.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?