Reverse String
LeetCode 344 · Easy · solution, intuition & step-by-step walkthrough
Swap s[i] with s[n−1−i] for i < n/2.
This is how I solved Reverse String (LeetCode 344), an easy problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Swap the first and last characters, then the second and second-to-last, and so on until the middle. Each swap fixes two positions.
Approach
- 1
Loop i over the first half.
- 2
Swap s[i] and s[n−i−1].
How I solved it
Two-ended swapPythonO(n) time · O(1) space
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
n=len(s)
for i in range(n//2):
s[i],s[n-i-1]=s[n-i-1],s[i]
return s
Reverse String — FAQ
What is the intuition behind Reverse String?
Swap the first and last characters, then the second and second-to-last, and so on until the middle. Each swap fixes two positions.
How do you solve Reverse String (LeetCode 344)?
1. Loop i over the first half. 2. Swap s[i] and s[n−i−1].
What is the time and space complexity of Reverse String?
Time: O(n). Space: O(1). (Accepted approach: Two-ended swap.)
What are common mistakes in Reverse String?
Stop at n // 2 or you'll swap everything back.