Palindromes
A palindrome reads the same both ways. Check one with two indexes moving inwards. Find long ones by growing outwards from every possible centre, which is O(n²) in the worst case and very simple. Manacher's algorithm does the same in O(n).
How to recognise it
- The question asks whether a string (or a cleaned-up version of it) reads the same backwards.
- The question asks for the longest palindromic substring, or to count palindromic substrings.
- Characters must be skipped or compared without caring about case.
The idea in one picture
Fold a strip of paper with letters on it in half. It is a palindrome if the letters that land on each other match. Two indexes, one from each end, do the folding: compare, step inwards, repeat.
Checking: two indexes moving inwards
l = 0, r = n - 1
while l < r:
if s[l] is not counted: l = l + 1
else if s[r] is not counted: r = r - 1
else if s[l] differs from s[r]: return false
else: l = l + 1; r = r - 1
return true
Finding: grow from each centre
Every palindrome has a centre: a character (odd length) or the gap between two characters (even length). From each centre, grow while both ends match.
| Centre | Start | Example |
|---|---|---|
| a character | l = r = i | "aba" around the b |
| a gap | l = i, r = i + 1 | "abba" around the gap between the b's |
for i from 0 to n - 1:
for (l, r) in ((i, i), (i, i + 1)):
while l >= 0 and r < n and s[l] == s[r]: l = l - 1; r = r + 1
the palindrome is s[l + 1 .. r - 1]
Common mistakes
- Expanding only around characters, which misses every even-length palindrome.
- Reading
s[l + 1 .. r - 1]wrongly: when the loop stops,landrare one step past the match. - Lowercasing only one side when comparing.
- Checking every substring with a reverse, which is O(n³).
Problems
- Valid Palindromeeasyguide ready
- Longest Palindromic Substringmediumguide ready