S1Q2 · Is Odd-Length Palindrome¶
⚡ Quick Reference
Function: is_odd_length_palindrome(s: str) -> bool
Core idea: two conditions must both be true - odd length AND palindrome.
Key rules:
- Odd length → len(s) % 2 == 1
- Palindrome → s == s[::-1]
- Both must hold → use and
Problem Statement¶
Problem
Write a function is_odd_length_palindrome(s) that returns True if s is both a palindrome and has an odd number of characters, False otherwise.
Examples:
"hello"
False
"noon"
False
"nun"
True
Tracing all examples¶
| String | Palindrome? | Odd length? | Result |
|---|---|---|---|
"hello" |
❌ (olleh ≠ hello) |
✅ (5) | False |
"noon" |
✅ (noon = noon) |
❌ (4) | False |
"nun" |
✅ (nun = nun) |
✅ (3) | True |
Solution approaches¶
Key takeaways¶
Two independent conditions - use and
Both must be true simultaneously. and short-circuits - if length is even, the palindrome check is never performed.
s == s[::-1] for palindrome
The one-liner palindrome check. Works for any sequence. Odd-length palindromes always have a unique middle character - but you don't need to find it explicitly.
Check the cheap condition first
Length check is O(1); reversal is O(n). Putting the length check first means even-length strings never trigger the reversal - a small but clean optimisation.