14

Phase 3 - Level 4: String-based Recursion

Chapter 14 • Advanced

105 min

Phase 3 - Level 4: String-based Recursion

Introduction

This level focuses on recursive string manipulation. You'll learn to process strings character by character using recursion.

Key Concepts

String Recursion Patterns

  • Process first character, recurse on rest
  • Process last character, recurse on remaining
  • Check conditions recursively
  • Build new strings recursively

Common Operations

  • Reverse String: Build from end to start
  • Palindrome Check: Compare first and last, recurse on middle
  • Count Characters: Count vowels, consonants, etc.
  • Remove/Replace: Process and build new string
  • Character Operations: Convert case, filter characters

Recursive String Processing

Reverse String

python.js
def reverse_string(s):
    if len(s) <= 1:
        return s
    return reverse_string(s[1:]) + s[0]

Palindrome Check

python.js
def is_palindrome(s):
    if len(s) <= 1:
        return True
    if s[0] != s[-1]:
        return False
    return is_palindrome(s[1:-1])

Problem-Solving Approach

  1. Base Case: Empty string or single character
  2. Process Character: Handle first/last character
  3. Recurse: Process remaining substring
  4. Combine: Build result from processed character + recursive result

String Slicing

  • s[0]: First character
  • s[-1]: Last character
  • s[1:]: All except first
  • s[:-1]: All except last
  • s[1:-1]: All except first and last

Common Patterns

  • Character-by-Character: Process one char, recurse on rest
  • Conditional Processing: Check condition, then recurse
  • String Building: Build result recursively
  • Character Counting: Count while recursing

Hands-on Examples

Reverse String Recursively

def reverse_string(s):
    # Base case
    if len(s) <= 1:
        return s
    
    # Recursive case: reverse rest, then add first character
    return reverse_string(s[1:]) + s[0]

# Test
text = input("Enter a string: ")
result = reverse_string(text)
print(f"Reversed: {result}")

Base case: single or empty string returns itself. Recursive: reverse substring (s[1:]) and append first character (s[0]).