Program to check whether all palindromic substrings are of odd length or not in Python

Sometimes we need to check if all palindromic substrings in a string have odd lengths. A key insight is that any even-length palindrome must contain adjacent identical characters. Therefore, we can solve this by simply checking for consecutive duplicate characters.

Algorithm

The approach is straightforward ?

  • Iterate through the string from index 1 to the end
  • If any character equals the previous character, return False
  • If no adjacent duplicates are found, return True

Why This Works

Any even-length palindrome like "aa", "abba", or "deed" must have at least one pair of adjacent identical characters. By ensuring no such pairs exist, we guarantee all palindromes have odd length.

Example

class Solution:
    def solve(self, s):
        for i in range(1, len(s)):
            if s[i] == s[i - 1]:
                return False
        return True

# Test the solution
ob = Solution()
s = "level"
print(ob.solve(s))
True

Additional Examples

Let's test with different strings ?

class Solution:
    def solve(self, s):
        for i in range(1, len(s)):
            if s[i] == s[i - 1]:
                return False
        return True

ob = Solution()

# Test cases
test_strings = ["level", "racecar", "hello", "aab", "abccba"]

for s in test_strings:
    result = ob.solve(s)
    print(f"'{s}' ? {result}")
'level' ? True
'racecar' ? True
'hello' ? False
'aab' ? False
'abccba' ? False

Analysis

String Has Adjacent Duplicates? All Palindromes Odd Length?
"level" No True
"hello" Yes (ll) False
"aab" Yes (aa) False

Conclusion

To check if all palindromic substrings have odd length, simply verify that no adjacent characters are identical. This works because even-length palindromes always contain consecutive duplicate characters.

Updated on: 2026-03-25T11:28:49+05:30

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements