Check a palindrome recursively by indices

Problem

Implement is_palindrome(text) recursively without loops, slicing, or reversing. The comparison is case-sensitive and includes every character.

Reveal answer or reference solution

Use two indices. Zero or one remaining characters is a palindrome. If the endpoint characters differ, return false; otherwise recurse inward. The algorithm takes O(n)O(n) time and O(n)O(n) call-stack space.

def is_palindrome(text: str) -> bool:
    def check(left: int, right: int) -> bool:
        if left >= right:
            return True
        if text[left] != text[right]:
            return False
        return check(left + 1, right - 1)
 
    return check(0, len(text) - 1)

Public tests

  • is_palindrome("") → True
  • is_palindrome("x") → True
  • is_palindrome("racecar") → True
  • is_palindrome("abca") → False
  • is_palindrome("Aa") → False
Outcome

Previous attempts

Loading attempts saved in this browser…

    Review Screening Results