Recursion on Strings: Palindrome Check
A string is a palindrome if it reads the same backward as forward (e.g., "radar", "level", "madam").
To check this recursively, we compare characters from the outside inwards:
- Index Mapping: At index $i$, the corresponding symmetrically opposite character is located at
len - 1 - i. - Base Case:
i >= len / 2. When pointer $i$ reaches or crosses the middle of the string, it means all outer pairs matched. We returntrue. - Mismatch check: If
str[i] !== str[len - 1 - i], the string cannot be a palindrome. We returnfalseimmediately. - Recursive Step: If the characters match, call
isPalindrome(i + 1, str).
Complexity Analysis
Time Complexity: O(N)
In the worst case (palindrome string), the function compares $N/2$ pairs of characters, executing in $O(N)$ linear time.
Space Complexity: O(N)
The call stack size reaches a maximum height of $N/2$ stack frames. Thus, the auxiliary space complexity is linear, $O(N)$.