—
Check a palindrome recursively by indices
Tutor me on https://mlprep.iwase.dev/item/prog-rec-palindrome-indices/. This is a screening item. If window.mlPrepAgent is available, read attempts for item prog-rec-palindrome-indices before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record with recorded_by agent, include agent_session_id when available, and read it back.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 time and 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("")→Trueis_palindrome("x")→Trueis_palindrome("racecar")→Trueis_palindrome("abca")→Falseis_palindrome("Aa")→False
Previous attempts
Loading attempts saved in this browser…