DrawCode Algorithm Visualizer • String • Medium

Longest Palindromic Substring

Tags: String, Palindrome, DP, Expand Around Center

1. One-Liner

Find the longest contiguous palindrome in S — often solved in O(n²) by expanding around centers or O(n) with Manacher.


2. The Problem It Solves

Used in symmetry detection, DNA inverted repeats, and as a stepping stone to palindrome partitioning / minimum cuts problems.


3. The Core Idea

Every palindrome has a center (one character for odd length, between two for even). Expand while boundary characters match; track the maximum radius or length.


4. How It Works (Table)

StepWhat Happens
1For each center c from 0 to n-1 (odd) and each gap (even).
2While L ≥ 0, R < n, and S[L]==S[R], decrement L, increment R.
3Record best R-L-1 length and substring bounds.
4Alternative: DP dp[i][j] = palindrome iff S[i]==S[j] and (j-i<2 or dp[i+1][j-1]).

5. Dry Run Example

"babad" — longest length 3 ("bab" or "aba"). Expand around 'a' at index 2 for odd case.


6. Key Properties

PropertyValue
Expand centersO() time, O(1) space
ManacherO(n) time for same problem

7. Where It Is Used

DomainUse
InterviewsClassic medium string task
BioPalindromic repeats
UIFun palindrome highlights

8. Interview Tips

Mention two center types (odd/even). Upgrade to Manacher if interviewer pushes linear time.


9. Comparison with Other Algorithms

ApproachTime
BruteO()
Center expandO()
ManacherO(n)

10. Complexity

MetricValue
Center expansionO() time, O(1) extra
DP tableO() time and space

Implementation Example (PYTHON)

def longest_palindrome_center(s):
    if not s:
        return ''
    start, maxlen = 0, 1
    def expand(l, r):
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        return r - l - 1
    for i in range(len(s)):
        odd = expand(i, i)
        even = expand(i, i + 1)
        cur = max(odd, even)
        if cur > maxlen:
            maxlen = cur
            start = i - (cur - 1) // 2
    return s[start : start + maxlen]

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer