~/problems / 2-D dynamic programming / String DP (edit distance, LCS)

Longest Palindromic Substring

medium ~25 min

Write longest_palindrome(s: str) -> str that returns a longest contiguous substring of s that reads the same forwards and backwards. If several have the maximum length, return any one of them.

Examples:

  • longest_palindrome("racecars") returns "racecar"
  • longest_palindrome("abcd") may return "a", "b", "c" or "d"
  • longest_palindrome("xabbay") returns "abba" (even length)

Constraints: 1 <= len(s) <= 3000, letters and digits. Checking every substring is O(n³) and too slow for the long tests. Aim for O(n²).

Show hint

every palindrome grows outward from its middle, which is a character or the gap between two characters.

Topic: String DP (edit distance, LCS). dp[i][j] over prefixes of two strings; palindromes by expanding or by length.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc