Skills101
← All coding problems

Longest Palindromic Substring

mediumStrings+20 XPTime limit 3s

Find the longest substring (contiguous) that reads the same forwards and backwards. If several have the maximum length, print the one that starts leftmost.

Input: one line s (lowercase letters and digits).

Output: the longest palindromic substring.

Constraints: 1 ≤ length of s ≤ 2000.

Think about it: every palindrome has a centre — a character (odd length) or a gap between two characters (even length). Expand around each of the 2n − 1 centres: O(n²) time, O(1) memory. (Manacher's algorithm does it in O(n), if you are curious.)

Sample input 1

babad

Sample output 1

bab

Sample input 2

cbbd

Sample output 2

bb

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.