Practice · Dynamic programming (2D) · 3 of 4

Longest Palindromic Substring

A palindrome reads the same forwards and backwards, like level or abba. A substring is a run of consecutive characters.

Given a string s, return its longest substring that is a palindrome. If several are equally long, return the one that starts first.

Example 1

Input
s = "cabbad"
Output
"abba"
abba reads the same both ways, and nothing longer does.

Example 2

Input
s = "abcd"
Output
"a"
Only single letters are palindromes here; a starts first.

Example 3

Input
s = "abacdc"
Output
"aba"
aba and cdc are both 3 long; aba starts first.

Constraints

  • s holds 1 to 1000 characters, each a lowercase letter or a digit.