Palindromes
medium 22 minA palindrome reads the same forwards and backwards.
Video lesson · Chapter 1 of 10
The mirror label
Palindromes in 75 seconds
1:17Reel
How it works
Step through the idea, or press Play.
Check with two pointers. Compare the outer pair and walk inwards: one string in O(n) time, O(1) space
Understand it
Start here
Same forwards and backwards
A palindrome reads the same in both directions: racecar, abba, a, and even the empty string. Palindrome questions are a favourite in interviews because one idea, *a palindrome is matching ends around a smaller palindrome*, powers a whole family of solutions, from a two-pointer check to interval dynamic programming.
Substring
Contiguous letters. In
babadthe longest palindromic substrings arebabandaba, length 3.Subsequence
Letters kept in order, gaps allowed. In
bbbabthe longest palindromic subsequence isbbbb, length 4.Partition
Cut a string into pieces that are all palindromes.
aabneeds one cut:aa | b.
Step 1
Checking one string with two pointers
Put [L] at the first letter and [R] at the last. If they differ, it is not a palindrome. If they match, move both one step inwards and repeat until they meet. A string of length needs only comparisons: racecar needs 3.
The two-pointer check
def is_palindrome(s): left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return False # outer pair differs left += 1 right -= 1 return True # every pair matchedprint(is_palindrome("racecar"), is_palindrome("abba"), is_palindrome("abca")) # True True Falses == s[::-1] is shorter but builds a reversed copy, O(n) extra space.Brute force
Every substring, every check: O(n³)
Why brute force is cubic
def longest_palindrome_brute(s): best = "" for i in range(len(s)): for j in range(i, len(s)): sub = s[i:j + 1] if sub == sub[::-1] and len(sub) > len(best): best = sub return bestprint(longest_palindrome_brute("babad"), longest_palindrome_brute("cbbd")) # bab bbStep 2
Expand around the centre: O(n²)
Turn the check inside out. Instead of starting at the ends and walking in, start at a centre and walk out while the two ends match. Every palindrome has a centre, so trying every centre finds every palindrome, and each expansion step reuses the inner palindrome for free.
Expanding one centre
Counting the work
aaaa…a, where every expansion succeeds until it hits an edge.def longest_palindrome(s): def expand(l, r): while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1 return l + 1, r - 1 # the last range that matched start, end = 0, 0 for c in range(len(s)): for l, r in (expand(c, c), expand(c, c + 1)): # odd centre, even centre if r - l > end - start: start, end = l, r return s[start:end + 1]print(longest_palindrome("babad"), longest_palindrome("cbbd"), longest_palindrome("abba")) # bab bb abbaTwo kinds of centre
Odd centres and even centres
Odd: on a letter
Start with . Grows
a→bab→cbabc. Lengths 1, 3, 5, … There are of these.Even: in a gap
Start with , . Grows
bb→abba. Lengths 2, 4, 6, … There are of these.Miss one, miss half
Odd centres alone never find
abbaorbb: every even-length palindrome sits on a gap.
| Centre in babad | Kind | Grows to | Length |
|---|---|---|---|
0 (b) | odd | b | 1 |
1 (a) | odd | b = b, so `bab` | 3 |
2 (b) | odd | a = a, so aba | 3 (ties, not longer) |
3 (a) | odd | b ≠ d, stays a | 1 |
4 (d) | odd | d | 1 |
| the 4 gaps | even | ba, ab, ba, ad all differ | 0 |
babad. The answer is bab; aba is equally long, so either is accepted.Step 3
Interval DP: the is_pal table
The recurrence
What one cell depends on
| i \ j | 0 b | 1 a | 2 b | 3 a | 4 d |
|---|---|---|---|---|---|
| 0 b | T | F | T | F | F |
| 1 a | T | F | T | F | |
| 2 b | T | F | F | ||
| 3 a | T | F | |||
| 4 d | T |
babad. Only the upper triangle is used. The longest T is , bab; there are 7 T cells, so 7 palindromic substrings.Fill order
Short ranges first, then longer ones
- 1Length 1the diagonal is all True
- 2Length 2True if the two letters match
- 3Length 3 to nends match and inner range True
- 4Readlongest True cell, or count them
def longest_palindrome_dp(s): n = len(s) is_pal = [[False] * n for _ in range(n)] start, best = 0, 1 for i in range(n): is_pal[i][i] = True # length 1 for length in range(2, n + 1): # short ranges first for i in range(n - length + 1): j = i + length - 1 if s[i] == s[j] and (length == 2 or is_pal[i + 1][j - 1]): is_pal[i][j] = True if length > best: start, best = i, length return s[start:start + best]print(longest_palindrome_dp("babad"), longest_palindrome_dp("cbbd")) # bab bbExpand around centre
- extra space.
- Fewer steps: stops at the first mismatch.
- Best for the longest substring or the count.
is_pal table
- space: 100 million cells for .
- But answers "is a palindrome?" in afterwards.
- Needed as a building block for min cuts and partitioning.
Variant
Counting palindromic substrings
Count every palindromic substring, counting each position separately: aaa has 6 (a three times, aa twice, aaa once); abc has 3; babad has 7. With expand-around-centre, every successful step finds one new palindrome, so just add 1 each time the ends match.
Bounds
aaaa. This is also why expanding is : each successful step is one palindrome.def count_substrings(s): n, count = len(s), 0 for k in range(2 * n - 1): # centres: letters (even k) and gaps (odd k) l, r = k // 2, k // 2 + k % 2 while l >= 0 and r < n and s[l] == s[r]: count += 1 # s[l..r] is one more palindrome l -= 1 r += 1 return countprint(count_substrings("aaa"), count_substrings("abc"), count_substrings("babad")) # 6 3 7Subsequences
Longest palindromic subsequence
The LPS recurrence
One cell of the LPS table
def longest_palindrome_subseq(s): n = len(s) dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for length in range(2, n + 1): for i in range(n - length + 1): j = i + length - 1 if s[i] == s[j]: dp[i][j] = dp[i + 1][j - 1] + 2 # keep both ends else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) # drop one end return dp[0][n - 1]print(longest_palindrome_subseq("bbbab"), longest_palindrome_subseq("cbbd")) # 4 2| i \ j | 0 b | 1 b | 2 b | 3 a | 4 b |
|---|---|---|---|---|---|
| 0 b | 1 | 2 | 3 | 3 | 4 |
| 1 b | 1 | 2 | 2 | 3 | |
| 2 b | 1 | 1 | 3 | ||
| 3 a | 1 | 1 | |||
| 4 b | 1 |
bbbab. The corner: b, so , the subsequence bbbb.Shortcut
LCS with the reverse, and minimum insertions
Two identities worth knowing cold
LCS("bbbab", "babbb") = 4. For mbadm, LPS is 3 (mam), so 2 insertions make it a palindrome, such as mbdadbm.def lcs(a, b): m, n = len(a), len(b) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if a[i - 1] == b[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp[m][n]def lps(s): return lcs(s, s[::-1])def min_insertions(s): return len(s) - lps(s) # letters outside the LPS each need a mirrorprint(lps("bbbab"), min_insertions("mbadm"), min_insertions("leetcode")) # 4 2 5Extension
Palindrome partitioning: fewest cuts
Min cuts on top of is_pal
Computing cuts[i]
def min_cut(s): n = len(s) is_pal = [[False] * n for _ in range(n)] for i in range(n - 1, -1, -1): # bottom row up for j in range(i, n): if s[i] == s[j] and (j - i <= 2 or is_pal[i + 1][j - 1]): is_pal[i][j] = True cuts = [0] * n for i in range(n): if is_pal[0][i]: continue # whole prefix is one piece cuts[i] = i # worst case: every letter alone for j in range(1, i + 1): if is_pal[j][i]: cuts[i] = min(cuts[i], cuts[j - 1] + 1) return cuts[n - 1]print(min_cut("aab"), min_cut("a"), min_cut("abcbd"), min_cut("racecar")) # 1 0 2 0Choosing
Manacher's algorithm and which method to use
| Problem | Method | Time | Space |
|---|---|---|---|
| Is a palindrome? | Two pointers | ||
| Longest palindromic substring | Brute force | ||
| Longest palindromic substring | Expand around centre | ||
| Longest palindromic substring | is_pal table | ||
| Longest palindromic substring | Manacher | ||
| Count palindromic substrings | Expand around centre | ||
| Longest palindromic subsequence | Interval DP or LCS with reverse | , or with two rows | |
| Minimum insertions or deletions | |||
| Minimum cuts | is_pal + 1D cuts |
Which palindrome tool?
Key points
- A palindrome is matching ends around a smaller palindrome; every method reuses that inner answer.
- Check one string with two pointers from the ends: floor(n/2) comparisons, O(1) space.
- Longest palindromic substring: brute force O(n³); expanding around 2n − 1 centres is O(n²) time and O(1) space.
- Never forget even centres (gaps): odd centres alone miss abba and bb.
- is_pal[i][j] = s[i] == s[j] and is_pal[i + 1][j − 1]; fill by length or with i descending.
- Count palindromic substrings by adding 1 for every successful expansion step: aaa has 6.
- LPS: +2 when the ends match, otherwise the max of dropping either end; LPS(s) = LCS(s, reverse(s)).
- Minimum insertions = n − LPS. Minimum cuts stacks a 1D DP on the is_pal table. Manacher reaches O(n).