String Reversal Recursion

Watch how recursion processes each character and builds the reversed string from the end.

Character by Character
Time: O(n)

Controls

Reversed: “OLLEH

Current Step

Step 1 of 0

Enter a string and click Start to begin the visualization

Phase: Going Deeper

String Processing Visualization

Original String

H
E
L
L
O

Recursive Calls

No active calls

Python Implementation

def reverse_string(s):
    # Base case: empty string or single character
    if len(s) <= 1:
        return s
    
    # Recursive case: reverse the rest + first character
    return reverse_string(s[1:]) + s[0]

# Example usage
result = reverse_string("HELLO")  # Returns "OLLEH"

JavaScript Implementation

function reverseString(s) {
    // Base case
    if (s.length <= 1) {
        return s;
    }
    
    // Recursive case
    return reverseString(s.substring(1)) + s[0];
}

// Example usage
const result = reverseString("HELLO"); // Returns "OLLEH"

Algorithm Analysis

Time Complexity: O(n)

Each character is processed exactly once, requiring n recursive calls for a string of length n.

Space Complexity: O(n)

The recursion depth equals the string length, creating n stack frames. Each frame stores constant data.

Real-World Applications

  • • Palindrome checking algorithms
  • • Text processing and manipulation
  • • Undo functionality in text editors
  • • Data format conversion
  • • Encryption/decryption preprocessing