Create a Function to Find the Longest Palindromic Substring
Write a Python function that takes a string as input and returns the longest palindromic substring within it. A palindrome reads the same backward as forward. This intermediate challenge helps you practice string manipulation and algorithmic thinking.
Challenge prompt
Write a function named longest_palindromic_substring that accepts a single string argument and returns the longest substring of that string that is a palindrome. If there are multiple palindromes of the same maximum length, return the first one found. The input string will only contain lowercase alphabets.
Guidance
- • Consider checking all possible substrings for palindrome properties efficiently.
- • Try expanding around the center of possible palindromes to reduce complexity.
- • Remember to handle edge cases like empty strings or strings with one character.
Hints
- • A palindrome reads the same backward and forward, so compare characters symmetrically.
- • Expanding around each character (and each pair of characters) can help find palindromes without checking every substring.
- • Use helper functions to keep your code clean and modular.
Starter code
def longest_palindromic_substring(s):
# Your code here
passExpected output
longest_palindromic_substring('babad') # returns 'bab' or 'aba' longest_palindromic_substring('cbbd') # returns 'bb' longest_palindromic_substring('a') # returns 'a' longest_palindromic_substring('ac') # returns 'a' or 'c'
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.