mediumStringDynamic ProgrammingDynamic Programming

Longest Palindromic Substring

mediumTime: O(n^2)Space: O(1)

Recognize the pattern

find longest palindromic substringexpand from centerodd and even length palindromes

Brute force idea

If you approach Longest Palindromic Substring in the most literal way possible, you get this: Check every substring for palindrome. Each substring is independently verified. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

The real unlock in Longest Palindromic Substring comes when you notice this: Expand around center: for each position, expand outward while characters match. Try both odd-length (single center) and even-length (double center). Track the longest. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

At the center of Longest Palindromic Substring is one steady idea: Every palindrome has a center (single character for odd length, pair for even). Expanding from the center outward checks the palindrome condition naturally — stop when characters don't match. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

The trap in Longest Palindromic Substring usually looks like this: Only checking odd-length palindromes — 'abba' is even-length and has no single center. You must try both odd and even centers at each position. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Dynamic Programming Pattern