Skip to content

Reverse String

LeetCode

01 · Question

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.

02 · Solution

Reference solution

1def reverseString(s: List[str]) -> None:
2 def helper(l: int, r: int) -> None:
3 if l >= r:
4 return
5 s[l], s[r] = s[r], s[l]
6 helper(l + 1, r - 1)
7
8 helper(0, len(s) - 1)