Reverse String Problem
Description
LeetCode Problem 344.
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.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Constraints:
- 1 <= s.length <= 10^5
- s[i] is a printable ascii character.
Solution
Approach: Two Pointers
Building a reversed copy would use O(n) extra memory, which the problem forbids. Instead, swap characters in place from both ends toward the middle.
Put left at the first index and right at the last. While left < right:
- Swap
s[left]ands[right]. - Move
leftone step right andrightone step left.
Each swap puts two characters in their final places, so after about n / 2 swaps the whole array is reversed. For ["h","e","l","l","o"]: swap h/o, then e/l, and the middle l stays where it is.
A common slip in Python is writing s = s[::-1]. That builds a new list and points the local name s at it, so the caller's array is left unchanged (and O(n) extra memory is used). The swaps must modify the given list itself.
Complexity: O(n) time, where n is the length of s, and O(1) extra space.
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
Now write it from memory
Close the write-up and solve it yourself against the tests.