Longest Palindromic Substring
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Find the longest substring that reads the same in both directions.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1How many possible centres does a string of length n have?
- Hint 2Odd palindromes centre on a letter, even ones between two letters.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Drop a pebble in a pond: ripples spread equally to the left and right. Stand on each letter as if it were the pebble and spread outwards as long as the letters on both sides match. The ripple stops at the first mismatch. The widest ripple over all positions is the answer. Also try dropping the pebble between two letters, for palindromes of even length.
- The obvious way
Check every substring to see if it is a palindrome: O(n³).
- The key insight
There are 2n-1 centres (n letters and n-1 gaps). From each centre move one step left and one step right while the two letters match; the first mismatch ends that palindrome. Keep the longest. Each expansion costs at most O(n), so O(n²) in total with no extra memory.
- The algorithm
- For every position, spread outwards from that single letter (odd palindromes).
- Also spread outwards from the gap between that letter and the next (even palindromes).
- Spreading: while the letter on the left equals the letter on the right, step both outwards.
- Remember the longest piece found.
Watch it run
Exampletext = "babad"
Centre on the first b: nothing on its left, so "b" (length 1).
longest = "b"
Where people slip
- Forgetting the even-length centres misses palindromes like "abba".
- Manacher's algorithm is O(n) but is rarely expected in interviews.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def longest_palindrome(text):
best = ""
def spread(left, right): # ripple outwards from a centre
while left >= 0 and right < len(text) and text[left] == text[right]:
left -= 1
right += 1
return text[left + 1 : right]
for centre in range(len(text)):
for candidate in (spread(centre, centre), spread(centre, centre + 1)):
if len(candidate) > len(best):
best = candidate
return bestNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.