Longest Palindromic Substring

Find the longest palindromic substring.

Pattern

Expand Around Center

This problem follows the Expand Around Center pattern, commonly found in the 1-D Dynamic Programming category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

For each center (and between-centers), expand outward while palindrome holds.

Key Insight

Expanding from centers is simpler than the DP table approach — there are only 2n-1 centers (n odd + n-1 even), each expansion is O(n) worst case.

Step-by-step

  1. 1For each possible center (and between-center for even length):
  2. 2Expand outward while characters on both sides match
  3. 3Track the longest palindrome found

Pseudocode

result = ""
for i in range(len(s)):
    # Odd-length palindrome
    l, r = i, i
    while l >= 0 and r < len(s) and s[l] == s[r]:
        if r - l + 1 > len(result):
            result = s[l:r+1]
        l -= 1; r += 1
    # Even-length palindrome
    l, r = i, i + 1
    while l >= 0 and r < len(s) and s[l] == s[r]:
        if r - l + 1 > len(result):
            result = s[l:r+1]
        l -= 1; r += 1
return result
Complexity Analysis

Time Complexity

O(n²)

Space Complexity

O(1)
More 1-D Dynamic Programming Problems

Master this pattern with YeetCode

Practice Longest Palindromic Substring and similar 1-D Dynamic Programming problems with flashcards. Build pattern recognition through active recall.

Practice this problem