π© Reverse String (#344)
π Problem Linkβ
π Problem Statementβ
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.
π‘ Examplesβ
Example 1β
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2β
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
π Key Insights & Approachβ
Core Observation: To reverse in-place, we need to swap elements from the outside moving inward. The first element swaps with the last, second with second-to-last, and so on.
Why Two Pointers?
- In-place requirement: Can't create a new array (
O(1)space constraint) - Symmetry: Reversing is inherently symmetricβwork from both ends
- Efficiency: Each element is touched once -
O(n)time
When to Stop?
- When
left >= right(pointers meet or cross) - For odd-length arrays: middle element stays in place
- For even-length arrays: all elements get swapped
Pattern Recognition: This is the classic "Two Pointers - Opposite Ends" pattern, used for reversing, palindrome checking, and container with most water. Key trait: pointers move toward each other from both ends
π Solution: Pythonβ
Approach 1: Two Pointersβ
Time Complexity: O(n) | Space Complexity: O(1)
def reverse_string(s):
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1