Python - Palindrome Substrings
What is a Palindrome?
A palindrome is a string that reads the same forward and backward.
Examples:
"madam" → Palindrome ✅
"racecar" → Palindrome ✅
"hello" → Not a palindrome ❌
Problem Statement
Given a string s, find all the palindrome substrings in s.
Example
Input: "abba"
Output: ['a', 'b', 'b', 'a', 'bb', 'abba']
Input: "abc"
Output: ['a', 'b', 'c']
Approach 1: Brute Force (O(N³))
Check all possible substrings and see if they are palindromes.
def is_palindrome(s):
return s == s[::-1]
def palindrome_substrings(s):
n = len(s)
result = []
for i in range(n):
for j in range(i, n):
substring = s[i:j+1]
if is_palindrome(substring):
result.append(substring)
return result
# Example
print(palindrome_substrings("abba")) # Output: ['a', 'b', 'b', 'a', 'bb', 'abba']