The brute force method checks all substrings, making it slower for large inputs. The center expansion method optimizes by only considering the potential palindrome centers.
How to find all palindrome substrings in Python
Key takeaways:
Palindromes are words or phrases that can be read the same way from the front and back, such as "anna."
Two approaches for finding palindrome substrings are:
Brute force: Simple but inefficient for large inputs, with a time complexity of
. Expand from the center: Efficient and intuitive, with a time complexity of
.
Problem statement
Write a Python function to find all
Example:
Input: "ababa"
Output: ['aba', 'ababa', 'bab', 'aba']
Solution
We will go through two approaches for finding all palindrome substrings in Python:
Brute force
Expanding from the center
Approach 1: Brute force
The brute force method is the simplest approach to finding palindrome substrings in a given word. It involves checking every possible substring of the word and verifying if it’s a palindrome.
Here is the Python implementation of the brute force approach:
def is_palindrome(word):return word == word[::-1]def find_palindromes_bruteforce(input_word):palindromes = []n = len(input_word)for i in range(n):for j in range(i + 1, n):if is_palindrome(input_word[i:j+1]):palindromes.append(input_word[i:j+1])return palindromesstring = 'banana'palindromes = find_palindromes_bruteforce(string)print 'Palindrome substrings of ',string,' are:\n',palindromes
The code above contains two functions:
is_palindrome(word): This helper function checks if a given word is a palindrome by comparing it with its reverse.find_palindromes_bruteforce(word): This function takes an input word and finds all palindrome substrings by iterating through all possible substrings and checking if each one is a palindrome using theis_palindromefunction. It returns a list of all palindrome substrings found in the word.
Time and space complexity
The is_palindrome function checks if a given string is a palindrome by comparing it with its reverse, which takes
The find_palindromes_bruteforce function uses nested loops to generate all possible substrings of the input string and checks each substring for being a palindrome using the is_palindrome function. The outer loop runs is_palindrome is called, and it takes
The space complexity is
Note: While this method is easy to understand, it’s not efficient for larger words, as it takes
time.
Approach 2: Expand from the center
A more efficient approach involves taking each character in the word as the center of a potential palindrome. From this center, expand outwards in both directions to check for palindromes. This is done separately for odd-length palindromes (single character at the center) and even-length palindromes (two characters at the center). The expansion stops when the characters on either side are no longer the same.
Here is the Python implementation of this approach:
def find_palindromes(input, j, k):palindromes = []while j >= 0 and k < len(input) and input[j] == input[k]:palindromes.append(input[j: k + 1])j -= 1k += 1return palindromesdef find_palindromes_expand_from_center(input_string):palindromes = []for i in range(len(input_string)):palindromes += find_palindromes(input_string, i - 1, i + 1)palindromes += find_palindromes(input_string, i, i+1)return palindromesstring = 'banana'palindromes = find_palindromes_expand_from_center(string)print 'Palindrome substrings of ',string,' are:\n',palindromes
The code above contains two functions:
find_palindromes(input_string): This helper function uses awhileloop to iteratively find palindrome substrings in the input string. Thewhileloop expands the potential palindrome by decrementing the left index (j) and incrementing the right index (k) while checking if the characters at positionsjandkare equal. If the loop condition is met, the substring fromjtokis a palindrome and added to thepalindromeslist.find_palindromes_expand_from_center(input_string): This function initializes an empty list calledpalindromesto store the palindromic substrings found in theinput_string. It iterates over the indexes of the characters in theinput_stringtaking them as centers of potential palindrome substrings. For each indexi, it calls thefind_palindromesfunction twice:Using the current index
ias the center, andi - 1andi + 1as the initial left and right indexes for expansion (even-length palindromes).Using the current index
ias the center, andiandi+1as initial left and right for expansion (odd-length palindromes).
Time and space complexity
This approach improves upon the brute-force method by reducing unnecessary checks. Instead of iterating through all possible substrings, it considers only potential centers of palindromes. For each center, it expands outward to check if the characters on both sides are the same.
For each character in the string (and each pair of adjacent characters for even-length palindromes), we expand outward to find palindromes. In the worst-case scenario, where all characters are identical (e.g., "aaaaa"), we might need to traverse the entire length of the string for each center. Since there are
The space complexity is
Note: This is a significant improvement over the
time complexity of the brute-force method.
Looking to master your programming concepts with hands-on practice? Dive into Educative’s must-try courses:
Conclusion
In this Answer, we explored two approaches to finding all palindrome substrings in Python. The brute force approach involves checking every possible substring, while the expanding approach starts from each letter and expands to the left and right. Both approaches provide different perspectives on solving the problem.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What is the difference between the two methods for finding palindrome substrings?
Which approach should I use in an interview?
Can I implement these approaches in other languages like Java or C++?
What are the real-world applications of palindrome substring problems?
Free Resources