💡
Exercise 84

Reverse String Recursive 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Reverse a list of characters in-place using recursion. Do not allocate extra space — modify the input array directly.

s = ['h','e','l','l','o'] reverse_string(s) # s is now ['o','l','l','e','h'] # Recursive approach: # Swap first and last, then recurse on the middle # [h,e,l,l,o] → swap h,o → [o,e,l,l,h] # [e,l,l] → swap e,l → [o,l,l,e,h] # [l] → base case (single element) → done!

The two-pointer recursive pattern:

  • Use left and right pointers starting at both ends
  • Base case: left >= right (pointers crossed or met)
  • Recursive case: Swap s[left] and s[right], then recurse with left+1, right-1

This demonstrates how recursion replaces loops — the recursive call stack acts like a while loop with changing pointers.

📋 Instructions
Implement `reverse_string(s, left, right)` recursively to reverse the list of characters in-place. Test with ['h','e','l','l','o'] and ['H','a','n','n','a','h'].
Base case: if left >= right, return. Otherwise swap s[left] and s[right], then call reverse_string(s, left+1, right-1).
🧪 Test Cases
Input
''.join(s1)
Expected
olleh
Test case 1
Input
''.join(s2)
Expected
hannaH
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.