Skip to content
StackDecode
StringsAnimated

Longest Palindromic Substring

Expand outwards from every centre.

Time

O(n²)

Extra space

O(1)

Use it for

Simple approach; Manacher makes it O(n).

How it works

  1. A palindrome reads the same backwards. Every palindrome has a centre (a letter, or the gap between two letters).
  2. For each possible centre, expand outwards while the two ends match.
  3. Remember the longest palindrome found.
  4. O(n²) time, O(1) memory. (Manacher’s algorithm does it in O(n).)

Watch it run

Loading animation…