Palindromic Substrings
Count the palindromic substrings of a text
DSA, Medium, 1-D DP
Which structure or algorithm, and what does it cost.
A text s is made of lowercase letters. Count the pieces of s that are palindromes. A piece is an unbroken stretch of letters, and one letter alone counts. Pieces at different places count separately, even when they read the same.
Examples
Constraints
- 1 <= length of
s<= 2,000. shas only the lowercase letters a to z.
Your answer must contain
- The simple method and why it is too slow
- The better method
- The best method and why it is correct
- Code
- Time and memory cost
- A hand trace of example 1
Target Aim for O(n^2) time and O(1) memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Think of a palindrome as a mirror. What does every mirror have in its centre?
Hint 2 the approach
A wider palindrome holds a narrower one in its middle. Can one starting point help you count several palindromes at once?
Hint 3 the key step
Take each of the 2n - 1 middles, a letter or a gap. Step outward while the two ends match, and add one for every step that works.
Walkthrough
Full walkthrough brute force to best
Brute force
Check every piece of the text and count the palindromes. There are about n^2 / 2 pieces, and each check takes up to n / 2 steps. That is O(n^3) time: for a text of one repeated letter with n = 2,000 it is over 5 x 10^8 steps.
Better method
Memoised recursion over start and end positions. A piece is a palindrome when its end letters match and the piece inside is a palindrome. Save each answer, then count the pairs that are palindromes. That is O(n^2) time and O(n^2) memory.
Best method
Every palindrome has a middle: a letter or a gap between two letters, so there are 2n - 1 middles. From a middle, a palindrome of the next size exists exactly when the two letters just outside the last one match. So step outward from each middle and add one for every step where the ends match. Stop at the first mismatch, because every wider stretch around that middle fails too. Each palindrome is counted once, from its own middle. No table is needed.
Hand trace
Run on xyzzyx. It has 6 letters and 5 gaps between them, so 11 centres. Going left to right, the number of palindromes found at each centre is 1, 0, 1, 0, 1, 3, 1, 0, 1, 0, 1. The gap between the two z letters gives 3: zz, then yzzy, then xyzzyx, and then the walk stops at the edge. Every letter gives 1 for itself. The total is 1 + 0 + 1 + 0 + 1 + 3 + 1 + 0 + 1 + 0 + 1 = 9.
Code
def count_palindromes(s):
total = 0
for centre in range(2 * len(s) - 1):
lo, hi = centre // 2, centre // 2 + centre % 2
while lo >= 0 and hi < len(s) and s[lo] == s[hi]:
total += 1 # each match is one more palindrome around this middle
lo -= 1
hi += 1
return totalTime and memory
O(n^2) time: 2n - 1 middles, and each can step out up to n / 2 times, as in a text of one repeated letter. O(1) memory, because only a counter is kept.
Common mistakes
- Counting each different text once. The count is by place, so aaaa gives 10, not 4.
- Using only letter middles. On xyzzyx that drops the three palindromes around the gap between the two z letters, and gives 6 instead of 9.
- Walking on after a mismatch. Once the two ends differ, every wider stretch around that middle fails too, so stop.