Check if a string contains a palindromic sub-string of even length in Python

A palindrome is a string that reads the same forwards and backwards. In this problem, we need to check if a given string contains any palindromic substring of even length.

The key insight is that the shortest even-length palindrome is of length 2, consisting of two identical adjacent characters (like "aa", "bb", etc.). Any longer even-length palindrome must contain at least one pair of adjacent identical characters.

Algorithm

To solve this problem efficiently, we can use this approach ?

  • Iterate through the string from index 0 to length−2
  • For each position i, check if string[i] equals string[i+1]
  • If we find adjacent identical characters, return True
  • If no such pair is found, return False

Example

Let's implement this solution ?

def solve(string):
    for i in range(len(string) - 1):
        if string[i] == string[i + 1]:
            return True
    return False

# Test with example
s = "afternoon"
print(f"String: {s}")
print(f"Contains even-length palindrome: {solve(s)}")
String: afternoon
Contains even-length palindrome: True

How It Works

In the string "afternoon", when we check each adjacent pair ?

  • Position 0-1: 'a' ? 'f' ? Continue
  • Position 1-2: 'f' ? 't' ? Continue
  • Position 2-3: 't' ? 'e' ? Continue
  • Position 3-4: 'e' ? 'r' ? Continue
  • Position 4-5: 'r' ? 'n' ? Continue
  • Position 5-6: 'n' = 'n' ? Found! Return True

The substring "noon" (indices 5-8) is an even-length palindrome, and our algorithm detects it by finding the adjacent 'n' characters.

Additional Examples

def solve(string):
    for i in range(len(string) - 1):
        if string[i] == string[i + 1]:
            return True
    return False

# Test multiple cases
test_cases = ["afternoon", "hello", "programming", "aabbcc", "abcdef"]

for test in test_cases:
    result = solve(test)
    print(f"'{test}' contains even-length palindrome: {result}")
'afternoon' contains even-length palindrome: True
'hello' contains even-length palindrome: True
'programming' contains even-length palindrome: True
'aabbcc' contains even-length palindrome: True
'abcdef' contains even-length palindrome: False

Time Complexity

The algorithm has O(n) time complexity where n is the length of the string, as we iterate through the string once. The space complexity is O(1) as we only use a constant amount of extra space.

Conclusion

To check for even-length palindromic substrings, we only need to find adjacent identical characters. This works because any even-length palindrome must contain at least one pair of adjacent identical characters, making this an efficient O(n) solution.

---
Updated on: 2026-03-25T14:09:41+05:30

437 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements