LeetCode #344: Reverse String — Do it in-place using two pointers.
Given a list of characters, reverse it in-place. You must do this by modifying the input list, not creating a new one.
💭 Now it's your turn! Using the approach above, implement your solution in the editor. You've got this! 💪
How it works: Two pointers start at each end and swap their way toward the middle.
Complexity: Time O(n), Space O(1)
def reverseString(s):
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left] # Swap!
left += 1
right -= 1
s1
['o', 'l', 'l', 'e', 'h']
s2
['h', 'a', 'n', 'n', 'a', 'H']