Reverse a String
You are given a list of characters s. Reverse the list in-place. Do not return anything; modify the list directly.
Answer
Method 1, Trivial slicing:
class Solution: def reverseString(self, s: List[str]) -> None: reverse_string = s[::-1] for i in range(len(reverse_string)): s[i] = reverse_string[i]Method 2, Manual reverse: Build a reversed list manually by iterating from the end, then copy values back.
class Solution: def reverseString(self, s: List[str]) -> None: r = len(s) - 1 reverse_s = [] while r >= 0: reverse_s.append(s[r]) r -= 1 for i in range(len(reverse_s)): s[i] = reverse_s[i]Method 3, Two pointers: Swap the left and right characters until the pointers meet.
class Solution: def reverseString(self, s: List[str]) -> None: l, r = 0, len(s) - 1 while l <= r: s[l], s[r] = s[r], s[l] r -= 1 l += 1
Programming lesson:
Doing
s = reverse.copy()does not work for in-place modification because it only reassigns the local variablesto a new list. The original list (the one outside the function) remains unchanged. However, writings[i] = ...does modify the input list in-place, because we are updating the existing list’s elements.In Method 3, the swap
s[l], s[r] = s[r], s[l]happens simultaneously. In Python, the right-hand side is evaluated first (creating a temporary tuple), and then both assignments occur together. This prevents overwriting.
If done in two separate lines overwriting would happen.