Approach 1Optimal▶ Animated
Swap the ends
Two pointers, swap, step in, until they meet.
The classic in-place reverse. Each swap puts two characters into their final seats.
Algorithm
lo = 0,hi = n−1.- Swap, then
lo++,hi--, whilelo < hi.
- Time
- O(n)
- Space
- O(1)
class Solution: def reverseString(self, s: list[str]) -> list[str]: lo, hi = 0, len(s) - 1 while lo < hi: s[lo], s[hi] = s[hi], s[lo] lo += 1 hi -= 1 return s