Longest Palindromic Substring

Medium1-D dynamic programming

Given a string s, return its longest substring that reads the same forwards and backwards. A substring is a run of characters next to each other in s.

When several substrings share the longest length, return any one of them. Upper and lower case letters count as different characters.

Examples

Example 1
Input:  s = "rotorcar"
Output: "rotor"

rotor reads the same both ways.

Example 2
Input:  s = "abccbx"
Output: "bccb"

An even-length palindrome: its centre is the gap between the two c’s.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s holds English letters and digits only.

Stuck?

Hint 1

Every palindrome grows outwards from a centre. That centre is either one character (odd length) or the gap between two characters (even length).

Hint 2

For each of the 2n - 1 centres, expand while the characters on both sides match, and remember the longest stretch you reach.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur