Skip to content
BytePatterns

Longest Palindromic Substring

Strings: lesson 5 of 11

Stand on every centre and push outwards.

Lesson 5 of 11 · 5 min

Longest Palindromic Substring

Step 1 of 9

Every palindrome has a centre, so try them all: one per character, one per gap.

The Idea

Every palindrome has a centre. So try all of them: each character is an odd centre, and each gap between neighbours is an even centre.

From a centre, compare outwards while the two sides match. The moment they differ, that centre is finished — keep the longest stretch you collected.

Real-World Example

Genome tools hunt for reverse-complement palindromes the same way: sit on a position, grow outwards while the pairing holds, stop at the first mismatch. Checking every substring instead would be hopeless on a sequence of millions.

The Code

def longest_pal(s):
    best = ""
    def grow(left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left, right = left - 1, right + 1
        return s[left + 1:right]          # last stretch that matched
    for i in range(len(s)):
        for cand in (grow(i, i), grow(i, i + 1)):   # odd and even centres
            if len(cand) > len(best):
                best = cand
    return best

print(longest_pal("babad"))   # bab
print(longest_pal("cbbd"))    # bb

Python

Your turn

Fill in the blank.

def grow(s, left, right):
  while left >= 0 and right < len(s) and ___:
      left, right = left - 1, right + 1
  return s[left + 1:right]

print(grow("babad", 1, 1))   # want bab

Mini quiz

1 / 3

How many centres does an n-character string have?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.