MediumTwo PointersStringDynamic Programming

1 approach, code in every language

Problem description

Given a string, find the longest contiguous slice of it that is a palindrome, meaning it reads identically in both directions.

If several substrings share the maximum length, returning any one of them is acceptable. A single character is trivially a palindrome, so the answer is never empty when the input is non-empty.

Example 1

Input: s = "babad"

Output: "bab"

The slice "bab" is a palindrome of length three; "aba" would also be a valid answer.

Example 2

Input: s = "cbbd"

Output: "bb"

The longest mirror-image slice is "bb", since no palindrome of length three or more exists here.

Constraints

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

After the pattern

Now solve one you haven't seen.

Longest Mirror Run is our own problem on the technique behind Longest Palindromic Substring: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free