Find Longest Palindrome In A String

How will you find out the longest palindrome in a given string.

💡Strategies for Solving This Problem

Understanding the Problem

A palindrome reads the same forwards and backwards. For example, "racecar" and "noon" are palindromes. We need to find the longest such substring within a given string.

Approach 1: Expand Around Center

The key insight is that every palindrome has a center. We can check all possible centers (both single characters and pairs of characters for even-length palindromes).

Key Strategies:

  • Two Types of Centers: Odd-length palindromes (single character) and even-length palindromes (between two characters)
  • Expand Outward: From each center, expand outward while characters match
  • Track Maximum: Keep track of the longest palindrome found so far

Approach 2: Dynamic Programming

Build a 2D table where dp[i][j] represents whether substring from index i to j is a palindrome. This is more intuitive but uses O(n²) space.

Time Complexity:

  • Expand Around Center: O(n²) time, O(1) space
  • Dynamic Programming: O(n²) time, O(n²) space
  • Manacher's Algorithm: O(n) time (advanced)
Scroll to Top