We use recursion with two pointers (left and right) to swap characters from both ends, moving inward until they meet.
- Define a helper function with
leftandrightindices. - Base case: If
left >= right, return. - Swap
s[left]ands[right]. - Recurse with
left + 1andright - 1.
- Time Complexity: O(N).
- Space Complexity: O(N) (recursion stack).
def reverse_string(s):
def helper(left, right):
if left >= right:
return
s[left], s[right] = s[right], s[left]
helper(left + 1, right - 1)
helper(0, len(s) - 1)