← Visualizers
Two Pointers · expand around center LeetCode 5

Longest Palindromic Substring / visualized

Every other two-pointer machine on this list starts at the two ends and closes inward. This one inverts it: the pointers start together and move apart, because a palindrome is defined outward from its middle. The trap is counting the middles. A string of length n has 2n−1 centers, not n — n of them sit on a character (odd-length palindromes) and n−1 sit in the gap between two characters (even-length ones, which have no middle character at all). Miss the gaps and "cbbd" silently answers "b". From each center, push l left and r right while s[l] == s[r]; the first mismatch ends that center, and the longest span ever confirmed is the answer.

Execution

idle
s
centers
best
Press Run to begin.
0 / 0
Speed

Java · running line

current center l — expanding left r — expanding right confirmed palindrome / best mismatch that stops the center
O(n²) time · O(1) extra space  ·  2n−1 centers, each expanding at most n/2 steps. Manacher's algorithm gets the same answer in O(n) by reusing mirrored radii, but this is the version worth being able to write from memory.  c/2 and c%2 are the whole trick for enumerating gaps alongside characters.