Skip to content

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.

def is_odd_length_palindrome(s: str) -> bool:
    return len(s) % 2 == 1 and s == s[::-1]

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:

Input
"hello"
Output
False
Input
"noon"
Output
False
Input
"nun"
Output
True

Tracing all examples

String Palindrome? Odd length? Result
"hello" ❌ (ollehhello) ✅ (5) False
"noon" ✅ (noon = noon) ❌ (4) False
"nun" ✅ (nun = nun) ✅ (3) True

Solution approaches

def is_odd_length_palindrome(s: str) -> bool:
    return len(s) % 2 == 1 and s == s[::-1]
def is_odd_length_palindrome(s: str) -> bool:
    is_odd = len(s) % 2 == 1
    is_palindrome = s == s[::-1]
    return is_odd and is_palindrome
def is_odd_length_palindrome(s: str) -> bool:
    if len(s) % 2 == 0:      # even length → fail immediately
        return False
    return s == s[::-1]

Check the cheaper condition (length modulo) first. If it fails, skip the string reversal entirely.

is_odd_length_palindrome = lambda s: len(s) % 2 == 1 and s == s[::-1]

Key takeaways

01

Two independent conditions - use and

Both must be true simultaneously. and short-circuits - if length is even, the palindrome check is never performed.

02

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.

03

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.