← Whiteboard questions

Longest Palindromic Substring

Find the longest palindromic substring 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. A palindrome reads the same forwards and backwards. Return the longest palindrome that appears as one unbroken piece of s. If several have the longest length, return the one that starts first.

Examples

Input s = "zabcbad"
Output "abcba"
Why the letters a, b, c, b, a mirror around the middle c.
Input s = "mooncake"
Output "oo"
Why the middle is the gap between the two o letters, so an even length is allowed.
Input s = "stuv"
Output "s"
Why edge case: no letters repeat, so every single letter ties and the first one wins.

Constraints

Your answer must contain

Target Aim for O(n^2) time and O(1) extra memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

A palindrome mirrors around its middle. Where can the middle of a palindrome sit?

Hint 2 the approach

Checking every piece of the text costs too much. Think about how a long palindrome holds a shorter one at its middle.

Hint 3 the key step

There are 2n - 1 middles: each letter and each gap. From each, step outward while the two ends match. Keep the longest, the earlier on ties.

Walkthrough

Full walkthrough brute force to best

Brute force

Check every piece of the text. There are about n^2 / 2 pieces, and checking one means comparing its ends inward, up to n / 2 steps. That is O(n^3) time: for a text of one repeated letter with n = 3,000 it is over 10^9 steps.

Better method

Memoised recursion. A piece from i to j is a palindrome if its two end letters match and the piece from i + 1 to j - 1 is a palindrome. Save each answer, so every pair (i, j) is solved once. That is O(n^2) time and O(n^2) memory.

A table built by piece length. Mark every single letter as a palindrome, then every pair of equal neighbours, then longer pieces from the shorter ones inside them. This is O(n^2) time and O(n^2) memory, which is heavy for 3,000 letters.

Best method

Every palindrome has a middle: a letter (odd length) or the gap between two letters (even length). That gives 2n - 1 middles. From each middle, step outward one letter on each side while the two letters match. When they stop matching, the palindrome is the stretch just inside them. Keep the longest, and only replace it when a new one is strictly longer, so the earliest start wins ties. This is correct because any palindrome is found from its own middle. It needs no table, because the matching check is done while stepping outward.

Hand trace

Run on zabcbad. It has 7 letters and 6 gaps between them, so 13 centres. Going left to right, the palindrome lengths found are 1, 0, 1, 0, 1, 0, 5, 0, 1, 0, 1, 0, 1. Centre z gives length 1, the first best. Only the centre at c beats it: from c, b = b and a = a match, then z differs from d, so the palindrome is abcba with length 5. Nothing later is longer. The answer is abcba.

Code

def longest_palindrome(s):
    start, length = 0, 0            # the earliest longest palindrome found so far
    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]:
            lo -= 1
            hi += 1
        if hi - lo - 1 > length:
            start, length = lo + 1, hi - lo - 1
    return s[start:start + length]

Time and memory

O(n^2) time: there are 2n - 1 middles and each can step out up to n / 2 times, as in a text of one repeated letter. O(1) extra memory, plus the returned piece.

Common mistakes

  • Trying only letter middles. On mooncake that misses oo, because even-length palindromes have a gap as their middle.
  • Using the wrong bounds after the loop. The stepping stops one position too far on each side, so the palindrome is from lo + 1 up to hi - 1.
  • Replacing the best on a tie. Use strictly longer, otherwise on stuv the answer becomes v instead of s.

Related problems

More 1-D DP problems
Longest Palindromic Substring: walkthrough and solution