InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

Longest Palindromic Substring

medium Original ↗
Solving tips
  • Prefer expand-around-center over the 2-D table: every palindrome has one of 2n-1 centers, giving O(n^2) time and O(1) space.
  • Expand from both (i,i) for odd lengths and (i,i+1) for even lengths, or you miss palindromes like 'bb'.
  • The palindrome recurrence is s[i]==s[j] and inside s[i+1..j-1] is a palindrome (or length <= 1).
  • After expansion the last matching window is [left+1, right-1]; return the substring, not its length. Manacher reaches O(n) if needed.

Problem

Given a string s, return the longest contiguous substring of s that reads the same forwards and backwards. If several are tied for longest, returning any one of them is fine.

Examples

  • s = "babad""bab""aba" is an equally valid answer (both length 3).
  • s = "cbbd""bb" — the only even-length palindrome beats every single character.
  • s = "a""a" — a single character is a palindrome of length 1.

Constraints

  • 1 <= s.length <= 1000
  • s consists of digits and English letters.

Think about it first

Hint 1 Brute force checks every substring for the palindrome property — O(n²) substrings, O(n) to check each, O(n³) total. Too slow, but it frames the sub-question: "is s[i..j] a palindrome?"
Hint 2 That sub-question has beautiful recursive structure: s[i..j] is a palindrome iff s[i] == s[j] AND the inside s[i+1..j-1] is a palindrome (or is length ≤ 1). That's a 2-D boolean DP over (i, j).
Hint 3 Or flip it around: every palindrome has a center. There are 2n-1 centers (each character, and each gap between characters). Expand outward from each center while the two ends match, and track the longest span. O(n²) time, O(1) space, no table.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.