AlgoViz

Palindromes

medium 22 min

A palindrome reads the same forwards and backwards.

Video lesson · Chapter 1 of 10

The mirror label

0:00 / 8:17

Palindromes in 75 seconds

1:17Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

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 babad the longest palindromic substrings are bab and aba, length 3.

  • Subsequence

    Letters kept in order, gaps allowed. In bbbab the longest palindromic subsequence is bbbb, length 4.

  • Partition

    Cut a string into pieces that are all palindromes. aab needs 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 nn needs only ⌊n/2⌋\lfloor n/2 \rfloor comparisons: racecar needs 3.

The two-pointer check

The middle letter of an odd-length string is never compared: it always matches itself.
Python
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 False
O(n) time, O(1) space. s == s[::-1] is shorter but builds a reversed copy, O(n) extra space.
Edit and run it in your browser

Brute force

Every substring, every check: O(n³)

Why brute force is cubic

∑L=1n(n−L+1)⏟substrings of length L⋅L⏟check=n(n+1)(n+2)6=Θ(n3)\sum_{L=1}^{n} \underbrace{(n - L + 1)}_{\text{substrings of length } L} \cdot \underbrace{L}_{\text{check}} = \frac{n(n+1)(n+2)}{6} = \Theta(n^3)
There are n(n+1)2\frac{n(n+1)}{2} substrings and checking one of length LL costs up to LL steps. For n=1000n = 1000 that is about 167 million character steps.
Python
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 bb
Correct and easy to trust, which makes it a good tester for faster versions.
Edit and run it in your browser

Step 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

When the loop stops, L and R have gone one step too far, so the palindrome is the range strictly between them.

Counting the work

n⏟letters+n−1⏟gaps=2n−1 centres,each expands at most ⌈n2⌉  ⟹  O(n2) time,  O(1) space\underbrace{n}_{\text{letters}} + \underbrace{n-1}_{\text{gaps}} = 2n - 1 \text{ centres}, \qquad \text{each expands at most } \left\lceil \tfrac{n}{2} \right\rceil \;\Longrightarrow\; O(n^2) \text{ time}, \; O(1) \text{ space}
The worst case is a string like aaaa…a, where every expansion succeeds until it hits an edge.
Python
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 abba
The standard interview answer for Longest Palindromic Substring.
Edit and run it in your browser

Two kinds of centre

Odd centres and even centres

  • Odd: on a letter

    Start with L=R=cL = R = c. Grows a → bab → cbabc. Lengths 1, 3, 5, … There are nn of these.

  • Even: in a gap

    Start with L=cL = c, R=c+1R = c + 1. Grows bb → abba. Lengths 2, 4, 6, … There are n−1n - 1 of these.

  • Miss one, miss half

    Odd centres alone never find abba or bb: every even-length palindrome sits on a gap.

Centre in babadKindGrows toLength
0 (b)oddb1
1 (a)oddb = b, so `bab`3
2 (b)odda = a, so aba3 (ties, not longer)
3 (a)oddb ≠ d, stays a1
4 (d)oddd1
the 4 gapsevenba, ab, ba, ad all differ0
All 2⋅5−1=92 \cdot 5 - 1 = 9 centres of babad. The answer is bab; aba is equally long, so either is accepted.

Step 3

Interval DP: the is_pal table

The recurrence

pal(i,j)={truei=jsi=sjj=i+1si=sj  ∧  pal(i+1, j−1)j>i+1\text{pal}(i, j) = \begin{cases} \text{true} & i = j \\ s_i = s_j & j = i + 1 \\ s_i = s_j \;\wedge\; \text{pal}(i+1,\, j-1) & j > i + 1 \end{cases}
A range is a palindrome when its ends match and the range just inside is one. Ranges of length 1 and 2 are the base cases.

What one cell depends on

In the table the inner range is one row down and one column left: the diagonal neighbour below-left.
i \ j0 b1 a2 b3 a4 d
0 bTFTFF
1 aTFTF
2 bTFF
3 aTF
4 dT
The finished table for babad. Only the upper triangle i≤ji \le j is used. The longest T is (0,2)(0, 2), bab; there are 7 T cells, so 7 palindromic substrings.

Fill order

Short ranges first, then longer ones

The interval DP recipe
  1. 1Length 1the diagonal is all True
  2. 2Length 2True if the two letters match
  3. 3Length 3 to nends match and inner range True
  4. 4Readlongest True cell, or count them
Python
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 bb
O(n²) time and O(n²) space. Slower in practice than expanding, but the table answers many questions at once.
Edit and run it in your browser

Expand around centre

  • O(1)O(1) extra space.
  • Fewer steps: stops at the first mismatch.
  • Best for the longest substring or the count.

is_pal table

  • O(n2)O(n^2) space: 100 million cells for n=104n = 10^4.
  • But answers "is s[i..j]s[i..j] a palindrome?" in O(1)O(1) 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

n  ≤  #palindromic substrings  ≤  n(n+1)2n \;\le\; \#\text{palindromic substrings} \;\le\; \frac{n(n+1)}{2}
Every single letter counts, so at least nn. At most every substring, reached only by strings like aaaa. This is also why expanding is O(n2)O(n^2): each successful step is one palindrome.
Python
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 7
All 2n − 1 centres in one loop. Summing the True cells of is_pal gives the same number.
Edit and run it in your browser

Subsequences

Longest palindromic subsequence

The LPS recurrence

L(i,j)={1i=jL(i+1, j−1)+2si=sjmax⁡(L(i+1, j),  L(i, j−1))si≠sjL(i, j) = \begin{cases} 1 & i = j \\ L(i+1,\, j-1) + 2 & s_i = s_j \\ \max\big(L(i+1,\, j),\; L(i,\, j-1)\big) & s_i \ne s_j \end{cases}
Matching ends are both kept (+2). Otherwise one end cannot be in the answer, so drop the left end or the right end and keep the better result. An empty range (i>ji > j) counts 0.

One cell of the LPS table

Same table shape and fill order as is_pal, but the cells hold lengths and a mismatch is not fatal: it just loses one letter.
Python
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
O(n²) time and space. Row i reads only rows i and i + 1, so two rows are enough for O(n) space.
Edit and run it in your browser
i \ j0 b1 b2 b3 a4 b
0 b12334
1 b1223
2 b113
3 a11
4 b1
The LPS table for bbbab. The corner: s0=s4=s_0 = s_4 = b, so L(0,4)=L(1,3)+2=2+2=4L(0, 4) = L(1, 3) + 2 = 2 + 2 = 4, the subsequence bbbb.

Shortcut

LCS with the reverse, and minimum insertions

Two identities worth knowing cold

LPS(s)=LCS(s, reverse(s)),min insertions(s)=n−LPS(s)\text{LPS}(s) = \text{LCS}\big(s,\ \text{reverse}(s)\big), \qquad \text{min insertions}(s) = n - \text{LPS}(s)
LCS("bbbab", "babbb") = 4. For mbadm, LPS is 3 (mam), so 2 insertions make it a palindrome, such as mbdadbm.
Python
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 5
The reverse trick with a standard LCS, and minimum insertions on top. The same n − LPS also gives the minimum deletions.
Edit and run it in your browser

Extension

Palindrome partitioning: fewest cuts

Min cuts on top of is_pal

cuts[i]={0s[0..i] is a palindromemin⁡1≤j≤is[j..i] palindromecuts[j−1]+1otherwise\text{cuts}[i] = \begin{cases} 0 & s[0..i] \text{ is a palindrome} \\ \displaystyle\min_{\substack{1 \le j \le i \\ s[j..i] \text{ palindrome}}} \text{cuts}[j-1] + 1 & \text{otherwise} \end{cases}
Try every last piece s[j..i]s[j..i] that is a palindrome: one cut before it plus the best for the prefix before it. The answer is cuts[n−1]\text{cuts}[n-1].

Computing cuts[i]

Two DPs stacked: the 2D is_pal table answers palindrome questions in O(1), the 1D cuts array uses them. O(n²) time overall.
Python
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 0
Palindrome Partitioning II. Filling is_pal with i running downwards guarantees row i + 1 is ready.
Edit and run it in your browser

Choosing

Manacher's algorithm and which method to use

ProblemMethodTimeSpace
Is ss a palindrome?Two pointersO(n)O(n)O(1)O(1)
Longest palindromic substringBrute forceO(n3)O(n^3)O(1)O(1)
Longest palindromic substringExpand around centreO(n2)O(n^2)O(1)O(1)
Longest palindromic substringis_pal tableO(n2)O(n^2)O(n2)O(n^2)
Longest palindromic substringManacherO(n)O(n)O(n)O(n)
Count palindromic substringsExpand around centreO(n2)O(n^2)O(1)O(1)
Longest palindromic subsequenceInterval DP or LCS with reverseO(n2)O(n^2)O(n2)O(n^2), or O(n)O(n) with two rows
Minimum insertions or deletionsn−LPSn - \text{LPS}O(n2)O(n^2)O(n)O(n)
Minimum cutsis_pal + 1D cutsO(n2)O(n^2)O(n2)O(n^2)

Which palindrome tool?

Substring or subsequence is the first question to ask, because the two need different tools.

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).

Sources