Algorithm LogbookAlgorithm Logbook

Palindrom String

Recursion

📋 Problem Statement

Write a recursive function is_palindrome(s) that returns True if the string reads the same forward and backward, and False otherwise. Input: "racecar" → True. Input: "hello" → False. You must use recursion.

💡 Intuition

Check if s[left]=s[right]s[\text{left}] = s[\text{right}], then recursively check the inner substring s[left+1right1]s[\text{left}+1\ldots\text{right}-1]. The base case is when the pointers cross (leftright\text{left} \geq \text{right}) — a single character or empty string is always a palindrome.

🔧 Approach

  1. Pass left and right pointer indices along with the string.
  2. Base case: if left >= right, return True.
  3. If s[left] != s[right], return False immediately.
  4. Otherwise, recurse with left + 1 and right - 1.

Complexity Analysis

Time

O(N)O(N) — at most N/2\lfloor N/2 \rfloor recursive calls, each doing O(1)O(1) work

Space

O(N)O(N) for the recursion call stack (N/2\lfloor N/2 \rfloor frames)

⚠️ Common Mistakes

  • Not passing the left and right pointers, trying to slice the string instead
  • Using left > right as the base case instead of left >= right (misses the single-character case)
  • Forgetting to handle case sensitivity if required
  • Creating new string slices at each level, adding O(N)O(N) per call

🎯 Final Thoughts

This shows how the same algorithm (two-pointer palindrome check) can be expressed iteratively (O(1)O(1) space) or recursively (O(N)O(N) space). The recursive "check boundaries, recurse inward" pattern also appears in binary search and divide-and-conquer.