Longest Palindromic Substring

35 min · longestPalindrome()

A mirrored run can sit quietly inside a much longer message. Your job is to recover the largest one without rearranging or skipping a character.

Given a lowercase string s, return its longest palindromic substring. A substring is one continuous slice of the original string, and a palindrome reads the same in both directions.

Every input has exactly one substring of maximum palindromic length, so the returned string is unambiguous. Single characters count as palindromes.

Constraints

  • 1 <= s.length <= 1_000
  • s contains only lowercase English letters.
  • Exactly one palindromic substring has the maximum length.

Hints

Start with every interval

The direct approach chooses each pair of boundaries and checks inward. Notice how often nearby intervals compare the same inner characters.

Reuse the inner answer

An interval is palindromic when its two ends match and its inside is palindromic. Fill shorter intervals before longer ones, or choose an order that guarantees the inner state is ready.

Search from the midpoint

Every palindrome has one center: either a character or a gap. Expand from all 2n - 1 centers and keep the widest successful interval.

Follow-up

Could you reach O(n) time? Manacher's algorithm is a method that reuses palindrome radii across neighboring centers to do exactly that.

Visible cases

Examples

Example 1

ready
Input
s = "cbbd"
Expected
"bb"
Why
the middle pair is the unique longest palindrome

Example 2

ready
Input
s = "a"
Expected
"a"
Why
a single character is already palindromic

Example 3

ready
Input
s = "forgeeksskeegfor"
Expected
"geeksskeeg"
Why
the mirrored middle block is longest

Interview signal

Asked at

AmazonMicrosoftGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite