InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

Longest Palindromic Substring

medium Original ↗ 00:00

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 isolates the sub-question: is s[i..j] a palindrome?
Hint 2 That sub-question is recursive: s[i..j] is a palindrome iff s[i] == s[j] and the inside s[i+1..j-1] is a palindrome (or has length ≤ 1). That gives a 2-D boolean DP over (i, j).
Hint 3 Alternatively, 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, tracking the longest span. O(n²) time, O(1) space, no table.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug