Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Check Palindrome String Recursively

Check text palindromes recursively with case-insensitive outer comparisons. Students trim matching ends, stop on a mismatch, and retain spaces and punctuation.

AdvancedPhase 3 - Level 4: String-based RecursionExample 2 of 10
check-palindrome-string-recursively.py
1def is_palindrome(s):
2 # Base case
3 if len(s) <= 1:
4 return True
5
6 # Check first and last
7 if s[0].lower() != s[-1].lower():
8 return False
9
10 # Recurse on middle
11 return is_palindrome(s[1:-1])
12
13# Test
14text = input("Enter a string: ")
15if is_palindrome(text):
16 print("Palindrome")
17else:
18 print("Not a palindrome")

Output

Enter a string: racecar
Palindrome

Enter a string: hello
Not a palindrome

In this one

  • Compare outer characters
  • Normalize comparison case
  • Shrink both ends

How it works

  1. 1

    Return true for zero or one remaining character.

  2. 2

    Reject unequal lowercase outer characters.

  3. 3

    Otherwise recurse on s[1:-1].

Edge cases

Does empty text pass?

Does empty text pass?

Yes. It has no conflicting pair.

Are spaces ignored?

Are spaces ignored?

No. They remain part of the comparison.

What's going on

The function compares the first and last characters after lowercasing them. A mismatch returns false immediately; a match recurses on the middle slice.

Zero or one remaining character returns true. For Level, each outer pair matches. Spaces and punctuation are not removed, so a phrase that is a palindrome only after cleanup may fail. The shrinking slices and calls consume memory.

Does empty text pass? Yes. It has no conflicting pair.

Are spaces ignored? No. They remain part of the comparison.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What happens after a matching pair?

Pick an answer to check it.

Question 2

Does empty text pass?

Pick an answer to check it.

Questions people ask

Does empty text pass?

Yes. It has no conflicting pair.

Are spaces ignored?

No. They remain part of the comparison.

What happens after a matching pair?

Check s[1:-1].