#344
Reverse String
EasyTwo PointersStringTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using the two-pointer technique allows us to reverse the string in-place without needing extra space for a new string. This is efficient and meets the problem's constraints.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers, one at the start (left) and one at the end (right) of the array.
- 2Step 2: Swap the characters at the left and right pointers.
- 3Step 3: Move the left pointer one step to the right and the right pointer one step to the left.
- 4Step 4: Repeat until the left pointer is greater than or equal to the right pointer.
solution.py6 lines
1def reverseString(s):
2 left, right = 0, len(s) - 1
3 while left < right:
4 s[left], s[right] = s[right], s[left]
5 left += 1
6 right -= 1ℹ
Complexity note: The time complexity is O(n) because we only traverse the string once. The space complexity is O(1) since we are reversing the string in-place without using extra space.
- 1Using in-place operations saves memory and is often required in interviews.
- 2The two-pointer technique is a common pattern for problems involving arrays or strings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.