Recursion · String · Two ends

Palindrome Visualizer

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

Base case When the window is empty or a single character (l >= r), return 1.
Recursive case If s[l] != s[r], return 0. Otherwise check the strictly smaller window (l + 1, r - 1).

Recursion tree

Interactive recursion tree
Step 0/0 Answer —

The whole tree is drawn when the page opens. Next and Play start again from the first call.

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)

Complexity

PieceCostWhy
TimeO(n)Each call looks at one pair of ends.
StackO(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)