Find the Longest Palindromic SubstringLoading saved progress…

Find the Longest Palindromic Substring

A palindrome reads the same forwards and backwards — racecar, abba, a single letter. Given a string s, your job is to find the longest run of adjacent characters inside it that forms a palindrome, and return that run. For "babad", the answer is "bab": it's a three-character palindrome sitting in the middle, and nothing longer exists.

Two strings can be tied for longest. When that happens you return the one that starts earliest — the leftmost. This keeps the answer deterministic so there's exactly one correct output per input.

Signature

function longestPalindromicSubstring(s: string): string;
// Returns the longest contiguous substring of `s` that is a palindrome.
// On a tie for length, returns the one with the smallest start index.

Examples

longestPalindromicSubstring('babad'); // 'bab'
// 'bab' and 'aba' are both length-3 palindromes. 'bab' starts at index 0,
// 'aba' starts at index 1 — so 'bab' wins the tie.
longestPalindromicSubstring('cbbd'); // 'bb'
// The only palindrome longer than one character is 'bb' (an even-length one).
// Every single character is also a palindrome, but 'bb' is longer.

Notes

  • Substring, not subsequence — the characters must be contiguous. "ace" is a subsequence of "abcde" but not a substring; you only consider runs of adjacent characters.
  • Tie-break is leftmost — when several substrings share the maximum length, return the one with the lowest start index (the first you'd meet scanning left to right).
  • Empty inputlongestPalindromicSubstring('') returns ''. There is no character to anchor a palindrome on.
  • A single character is always a palindrome — so any non-empty string has an answer of length at least 1. If no run longer than one character is a palindrome, return the first character.
  • Both odd and even lengths count"aba" (odd) and "abba" (even) are both palindromes. Don't assume palindromes have a single middle character.
  • Assume the string is given — no need to validate types or handle null; s is always a string.
Loading editor…