What is Palindrome
Return 1 when s reads the same forward and backward, otherwise 0. The empty string is a palindrome.
Example. abba returns 1. The first and last letters match, then the inner bb matches. abc returns 0 because a and c differ.
Input: abba Output: 1
Constraints. 0 ≤ length ≤ 500, lowercase English letters. This picture draws at most 7 letters.
Approach
l >= r), return 1.s[l] != s[r], return 0. Otherwise check the strictly smaller window (l + 1, r - 1).Recursion tree
The whole tree is drawn when the page opens. Next and Play start again from the first call.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each call looks at one pair of ends. |
| Stack | O(n) | The window shrinks by two characters. |
Implementation
def is_pal(s, l, r):
if l >= r:
return 1
if s[l] != s[r]:
return 0
return is_pal(s, l + 1, r - 1)